Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set HttpHeader on individual request using HttpClient

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?

like image 306
Mike Christensen Avatar asked Feb 15 '17 16:02

Mike Christensen


People also ask

How do you add a header in HTTP request?

To add custom headers to an HTTP request object, use the AddHeader() method. You can use this method multiple times to add multiple headers.

How do I pass HttpClient header?

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.


1 Answers

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();
like image 53
Arturo Menchaca Avatar answered Oct 12 '22 11:10

Arturo Menchaca