每个请求C#的HttpClient PCL修改请求头

编程入门 行业动态 更新时间:2024-10-22 15:32:07
本文介绍了每个请求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("example"), 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修改请求头

本文发布于:2023-11-08 13:47:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569542.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:HttpClient   PCL

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!