29

I have some working code:

using (var client = new HttpClient())
{
HttpResponseMessage response;
response = client.PostAsync(Url, new StringContent(Request, Encoding.UTF8, header)).Result;
}

// the above works fine for a simple header, e.g. "application/json"

What do I do, if I want to have multiple headers? E.g. adding "myKey", "foo" pair and "Accept", "image/foo1"

If I try adding the following before the .Result line, intellisense complains (the word 'Headers' is in red with "Can't resolve symbol 'Headers'":

client.Headers.Add("myKey", "foo");
client.Headers.Add("Accept", "image/foo1");
n as
  • 609
  • 3
  • 7
  • 12

3 Answers3

45

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;
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
  • 6
    Ok... that helps to a degree (one set of headers was ok), but... I am now running into: Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects. I am not sure if the offending set is a a response or content header. How would I add either? – n as Mar 23 '15 at 18:07
  • I got error saying content header is separate from request header – Tony Jun 28 '21 at 16:15
25

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();
ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
Mr. Young
  • 2,364
  • 3
  • 25
  • 41
  • 1
    Looks like an interesting approach. I will experiment with it. – n as Mar 23 '15 at 18:24
  • 1
    FWIW, do not call `Task.Wait()` in the call stack above this. This could cause a dead-lock situation during `httpClient.SendAsync(httpRequestMessage)`. Instead make sure your stack is async/await from top to bottom or use a thread from the thread-pool. – Mr. Young Mar 01 '17 at 23:00
8

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

ΩmegaMan
  • 29,542
  • 12
  • 100
  • 122
kmcnamee
  • 5,097
  • 2
  • 25
  • 36