How do I set multiple headers using PostAsync in C#?
I stopped using the Post/Get *Async methods in favor of the SendAsync(...)
method and HttpRequestMessage
Send Async is the big brother which allows you the full flexibility you otherwise can't achieve.
using System.Net.Http;
var httpRequestMessage = new HttpRequestMessage();
httpRequestMessage.Method = httpMethod;
httpRequestMessage.RequestUri = new Uri(url);
httpRequestMessage.Headers
.UserAgent
.Add(new Headers.ProductInfoHeaderValue(
_applicationAssembly.Name,
_applicationAssembly.Version.ToString()));
HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
switch (httpMethod.Method)
{
case "POST":
httpRequestMessage.Content = httpContent;
break;
}
var result = await httpClient.SendAsync(httpRequestMessage);
result.EnsureSuccessStatusCode();
You can also use
var client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("headername","headervalue");
If you want to just set the headers on the HttpClient class just once. Here is the MSDN docs on DefaultRequestHeaders.TryAddWithoutValidation
You can access the Headers
property through the StringContent
:
var content = new StringContent(Request, Encoding.UTF8, header);
content.Headers.Add(...);
Then pass the StringContent to the PostAsync
call:
response = client.PostAsync(Url, content).Result;