I have an HttpClient
that is shared across multiple threads:
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."}
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.
Any ideas?
You can use SendAsync to send a HttpRequestMessage.
In the message you can setup the uri, method, content and headers.
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();
来源:https://stackoverflow.com/questions/42255160/how-to-set-httpheader-on-individual-request-using-httpclient