如何使用 HttpClient 根据个人请求设置 HttpHeader

How to set HttpHeader on individual request using HttpClient

我有一个跨多个线程共享的 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"));
    }
}

它有一些默认值 header 我在每个请求中添加了一些。但是,当我使用它时,我想为 添加 header 只是 该请求:

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();

当我这样做时,出现异常:

{"Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."}

我找不到另一种方法来向此请求添加请求 header。如果我在 Client 上修改 DefaultRequestHeaders,我 运行 就会陷入线程问题,并且必须实施各种疯狂的锁定。

有什么想法吗?

您可以使用 SendAsync to send a HttpRequestMessage.

在消息中您可以设置uri, method, content and headers

示例:

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();