每个请求C#的HttpClient PCL修改请求头 [英] Modify request headers per request C# HttpClient PCL

查看:469
本文介绍了每个请求C#的HttpClient PCL修改请求头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用的 System.Net.Http.HttpClient 的跨平台支持。

I'm currently using the System.Net.Http.HttpClient for cross platform support.

我看,这是不是一个好的做法,以实例化一个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.

现在我有一个问题,同时编写客户端库的服务。一些API调用需要有一个特定的头,有些不应包括这个特定的头。

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.

看来我只能操纵DefaultRequestHeaders将被发送给每个请求。

It seems that I can only manipulate the "DefaultRequestHeaders" which will be send with each request.

有没有在实际制作与如请求的选项client.PostAsync()修改标题只为具体的要求吗?

Is there an option when actually making the request with e.g. "client.PostAsync()" to modify the headers only for the specific request?

。(信息:请求可以被多线程)

(Info: Requests can be multi threaded).

在此先感谢!

推荐答案

是的,你可以创建一个新的Htt prequestMessage,将所有你需要的属性,然后将它传递给SendAsync。

Yes, you can create a new HttpRequestMessage, set all the properties you need to, and then pass it to 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);

这篇关于每个请求C#的HttpClient PCL修改请求头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆