How do I set multiple headers using PostAsync in C#?

n as picture n as · Mar 23, 2015 · Viewed 25.4k times · Source

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");

Answer

SwDevMan81 picture SwDevMan81 · Mar 23, 2015

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;