<In a recent project I was playing around with a Windows 8 Store app (formally known as Metro) and needed to POST some info to an REST based endpoint. The issue was I needed to set the Content-Type header to application/json to the API knew how to serialize the incoming data. Having not used the HttpClient object recently it took a little research to find how to set the Content-Type header. Its turns out this is pretty easy. Basically every HttpContent object has a .Headers property, which contains a property for most of the popular https headers, Content-Type being the one I was most interested in.
So how do you set it? It turns out that for any header property that you want to set, you use the MediaTypeHeaderValue object and pass in the value you want.
For example
_bodyContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json")
would set the Content-Type header value to be “application/json”.
Below is a more complete example of how to set the Content-Type header along with creating content for the body of the post, etc.
string URL = "http://[Your POST api method]";
//define that we are the body of the post will be string content. In our care
//if will be JSON
HttpContent _bodyContent = new StringContent("{field1:'myvalue',field2:'field2'}");
//set the content type header to be "application/json". We do this by setting the
//content-type property to application/json by initializing a new object called
//MediaTypeHeaderValue and passing what value we want to set the content-type header to be.
_bodyContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
//init the httpclient
HttpClient _client = new HttpClient();
//post the data to the API. Note for Win8, we are using the async/await paradigme
//so as not to block the ui thread.
var _resp = await _client.PostAsync(URL,_bodyContent);
//get the response from the api. In our case we assume that the data coming back will be string
// Note for Win8, we are using the async/await paradigme
//so as not to block the ui thread.
var a = await _resp.Content.ReadAsStringAsync();