【发布时间】:2017-07-04 10:55:24
【问题描述】:
我有一个在多个线程之间共享的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"));
}
}
它有一些我放在每个请求上的默认标头。但是,当我使用它时,我想为 just 该请求添加一个标头:
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();
当我这样做时,我得到了异常:
{"错误使用的标头名称。确保请求标头与 HttpRequestMessage,带有 HttpResponseMessage 的响应标头,以及 带有 HttpContent 对象的内容标头。"}
我找不到向此请求添加请求标头的其他方法。如果我修改Client 上的DefaultRequestHeaders,我会遇到线程问题并且必须实现各种疯狂的锁定。
有什么想法吗?
【问题讨论】:
标签: c# .net http-headers webclient