简体   繁体   English

如何使用HttpClient对单个请求设置HttpHeader

[英]How to set HttpHeader on individual request using HttpClient

I have an HttpClient that is shared across multiple threads: 我有一个跨多个线程共享的HttpClient

public static class Connection
{
    public static HttpClient Client { get; }

    static Connection()
    {
        Client = new HttpClient
        {
            BaseAddress = new Uri(Config.APIUri)
        };

        Client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
        Client.DefaultRequestHeaders.Add("Keep-Alive", "timeout=600");
        Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }
}

It has some default headers I put onto each request. 它具有一些我放入每个请求的默认标头。 However, when I use it, I want to add on a header for just that request: 但是,当我使用它时,我只想为该请求添加标题:

var client = Connection.Client;
StringContent httpContent = new StringContent(myQueueItem, Encoding.UTF8, "application/json");

httpContent.Headers.Add("Authorization", "Bearer " + accessToken); // <-- Header for this and only this request
HttpResponseMessage response = await client.PostAsync("/api/devices/data", httpContent);
response.EnsureSuccessStatusCode();

string json = await response.Content.ReadAsStringAsync();

When I do this, I get the exception: 当我这样做时,我得到一个例外:

{"Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."} {“滥用标头名称。请确保请求标头与HttpRequestMessage一起使用,响应标头与HttpResponseMessage一起使用,内容标头与HttpContent对象一起使用。”

I couldn't find another way to add request headers to this request. 我找不到另一种向此请求添加请求标头的方法。 If I modify the DefaultRequestHeaders on Client , I run into thread issues and would have to implement all sorts of crazy locking. 如果在Client上修改DefaultRequestHeaders ,则会遇到线程问题,并且必须实施各种疯狂的锁定。

Any ideas? 有任何想法吗?

You can use SendAsync to send a HttpRequestMessage . 您可以使用SendAsync发送HttpRequestMessage

In the message you can setup the uri , method , content and headers . 在消息中,您可以设置uri方法内容标题

Example: 例:

HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Post, "/api/devices/data");
msg.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
msg.Content = new StringContent(myQueueItem, Encoding.UTF8, "application/json");

HttpResponseMessage response = await client.SendAsync(msg);
response.EnsureSuccessStatusCode();

string json = await response.Content.ReadAsStringAsync();

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

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