简体   繁体   English

如何为HttpClient的特定连接设置HttpHeader?

[英]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, 我想为HttpClient建立和维护的整个http连接设置一个特定的标头(keep-alive设置为true),也就是说,

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. 不是一个选项,因为它为整个HttpClient设置了标头,而我只想为特定的连接使用它 ,这是在我第一次调用服务器上的URL时创建的。

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 . 然后,该服务器使连接保持活动状态,并希望我在连接为时对每个后续请求都具有MyHeader标头。

You can do something like this example. 您可以执行类似此示例的操作。 On each request you can clear all request headers from your HttpClient . 在每个请求上,您都可以从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,也不会为请求设置配置。

第一次通话后,将其删除

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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