Toshi
Toshi

Reputation: 2608

How to change the a Header of HttpContent

I have this code to change the Header of my content from {text/plain; charset=utf-8} to "{application/json}"

using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
{
    string content = "some json data";
    System.Net.Http.StringContent sc = new System.Net.Http.StringContent(content);
    sc.Headers.Remove("Content-Type"); // "{text/plain; charset=utf-8}"
    sc.Headers.Add("Content-Type", "application/json");
    System.Net.Http.HttpResponseMessage response = client.PostAsync("http://foo.bar", sc).Result;
}

Is there a way to modify it directly instead of removin and adding it?

Upvotes: 0

Views: 2035

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

If you are building json string manuallly by serializing some data, then there is much better way. You can use PostAsJsonAsync extension method:

using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient())
{
    var response = await client.PostAsJsonAsync("http://foo.bar", data);
}

It will automatically do following things

  • Serialize data to JSON
  • Create StringContent
  • Provide correct application/json media type

Upvotes: 1

Ipsit Gaur
Ipsit Gaur

Reputation: 2927

Use this overload of StringContent for setting content-type

sc = new StringContent(content, Encoding.UTF8, "application/json");

After this, you don't need to add/remove header values.

Upvotes: 3

Related Questions