我有一个跨多个线程共享的 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 , content和 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();
关于c# - 如何使用 HttpClient 根据个人请求设置 HttpHeader,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42255160/