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

标签 c# .net http-headers webclient

我有一个跨多个线程共享的 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 。但是,当我使用它时,我想为该请求添加一个标题:只是:

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发送 HttpRequestMessage .

在消息中你可以设置uri , method , contentheaders .

例子:

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

关于c# - 如何使用 HttpClient 根据个人请求设置 HttpHeader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42255160/

相关文章:

.net - Linq:获取DataContext中所有表的列表

ios - swift 2.0 与 Alamofire : How to send http headers with X-WSSE Authorization?

c# - 如何在 Windows 8 中访问日历

c# - 如何对被测方法中声明的变量的属性进行单元测试

c# - 使用 BinaryFormatter 而不是 protobuf-net 的原因

C#:以自定义百分比创建 CPU 使用率

c# - Windows 服务(TCP 客户端/监听器)防火墙异常阻止流量

.net - 此SqlTransaction已完成;它不再可用

angular - URLSearchParams 不是构造函数

perl - 如何为 Catalyst 中的每个响应设置 Cache-Control header ?