Set Authorization/Content-Type headers when call HTTPClient.PostAsync

Viewed 60528

Where can I set headers to REST service call when using simple HTTPClient?

I do :

HttpClient client = new HttpClient();
var values = new Dictionary<string, string>
{
    {"id", "111"},
    {"amount", "22"}
};
var content = new FormUrlEncodedContent(values);
var uri = new Uri(@"https://some.ns.restlet.uri");

var response = await client.PostAsync(uri, content);
var responseString = await response.Content.ReadAsStringAsync();

UPD

Headers I want to add:

{
    "Authorization": "NLAuth nlauth_account=5731597_SB1, nlauth_email=xxx@xx.com, nlauth_signature=Pswd1234567, nlauth_role=3",
    "Content-Type": "application/json"
}

Should I do the following?

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", "NLAuth nlauth_account=5731597_SB1, nlauth_email=xxx@xx.com, nlauth_signature=Pswd1234567, nlauth_role=3","Content-Type":"application/json");
5 Answers

The other answers do not work if you are using an HttpClientFactory, and here's some reasons why you should. With an HttpClientFactory the HttpMessages are reused from a pool, so setting default headers should be reserved for headers that will be used in every request.

If you just want to add a content-type header you can use the alternate PostAsJsonAsync or PostAsXmlAsync.

var response = await _httpClient.PostAsJsonAsync("account/update", model);

Unfortunately I don't have a better solution for adding authorization headers than this.

_httpClient.DefaultRequestHeaders.Add(HttpRequestHeader.Authorization.ToString(), $"Bearer {bearer}");

On dotnet core 3.1 trying to run the top answer:

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Content-Type", "application/x-msdownload");

threw an exception: System.InvalidOperationException: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.

What worked for me was to instead set HttpContent.Headers -> HttpContentHeaders.ContentType property with a MediaTypeHeaderValue value:

HttpClient client = new HttpClient();
var content = new StreamContent(File.OpenRead(path));
content.Headers.ContentType = new MediaTypeHeaderValue("application/x-msdownload");
var post = client.PostAsync(myUrl, content);

I prefer to cache the httpClient so I avoid setting headers which could affect other requests and use SendAsync

            var postRequest = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
            postRequest.Headers.Add("Content-Type", "application/x-msdownload");

            var response = await httpClient.SendAsync(postRequest);
            var content = await response.Content.ReadAsStringAsync();
Related