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?
To add custom headers to an HTTP request object, use the AddHeader() method. You can use this method multiple times to add multiple headers.
If you wish to add the User-Agent header to a single HttpRequestMessage , this can be done like this: var httpClient = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With