简体   繁体   English

根据请求修改请求标头C#HttpClient PCL

[英]Modify request headers per request C# HttpClient PCL

I'm currently using the System.Net.Http.HttpClient for cross platform support. 我目前正在使用System.Net.Http.HttpClient进行跨平台支持。

I read that it is not a good practice to instantiate a HttpClient object for each request and that you should reuse it whenever possible. 我读到,为每个请求实例化HttpClient对象并不是一个好习惯,并且应尽可能重用它。

Now I have a problem while writing a client library for a service. 现在我在为服务编写客户端库时遇到问题。 Some API calls need to have a specific header, some MUST not include this specific header. 某些API调用需要具有特定的标头,有些必须不包含此特定标头。

It seems that I can only manipulate the "DefaultRequestHeaders" which will be send with each request. 似乎我只能操纵将随每个请求发送的“DefaultRequestHeaders”。

Is there an option when actually making the request with eg "client.PostAsync()" to modify the headers only for the specific request? 实际发出请求时是否有一个选项,例如“client.PostAsync()”来修改仅针对特定请求的标头?

(Info: Requests can be multi threaded). (信息:请求可以是多线程的)。

Thanks in advance! 提前致谢!

Yes, you can create a new HttpRequestMessage, set all the properties you need to, and then pass it to SendAsync. 是的,您可以创建一个新的HttpRequestMessage,设置所需的所有属性,然后将其传递给SendAsync。

var request = new HttpRequestMessage() {
   RequestUri = new Uri("http://example.org"),
   Method = HttpMethod.Post,
   Content = new StringContent("Here is my content")
}
request.Headers.Accept.Add(...);  // Set whatever headers you need to

var response = await client.SendAsync(request);

Use HttpContent.Headers . 使用HttpContent.Headers Simply create HttpContent instance with required headers and pass it to PostAsync method. 只需使用所需的头创建HttpContent实例并将其传递给PostAsync方法。

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

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