简体   繁体   中英

How to set an HttpHeader on for a specific connection of HttpClient?

The most suggested question doesn't have the answer.

I would like to set a specific header for the entire http connection which HttpClient establishes and maintains (keep-alive is set to true), that is,

each request I make should contain my custom header. Obviously,

_httpClient.DefaultRequestHeaders.Add("MyHeader", "MyValue");

is not an option, since it sets the header for the entire HttpClient , whereas I would like to have it only for the specific connection , which is created when I make my first call to a URL at a server.

That server then keeps the connection alive and expects me to have a MyHeader header for each subsequent request that I make while the connection is .

You can do something like this example. On each request you can clear all request headers from your HttpClient . After that add the request headers which will help you.

client.DefaultRequestHeaders.Clear();

Simply you will not instantiate your HttpClient, also set configuration for request.

第一次通话后,将其删除

_httpClient.DefaultRequestHeaders.Remove("keep-alive");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM