C# HttpClient - How to set the Content-Type header for a request

This post describes how to make a HTTP request with a specific content-type using the HttpClient in C#. Using the HttpClient you can POST JSON or XML with built-in extension methods PostAsJsonAsync or PostAsXmlAsync, this will set the content-type to application/json and application/xml respectively. An example of how to POST JSON using PostAsJsonAsync can be seen below:

var httpClient = new HttpClient();
var jsonAsString = "{ \"text\":\"Some text\"}";
var response = await httpClient.PostAsJsonAsync("/someurl", jsonAsString);

The above can also take an object as a parameter instead of a string, the string was used for simplicity. If you are looking to make a request using a content-type different than JSON and XML you can use StringContent with a basic PutAsync or PostAsync. An example of StringContent with a content-type of text/plain can be seen below:

var httpClient = new HttpClient();
var content = new StringContent("This is plain text!", Encoding.UTF8, "text/plain");
var response = await httpClient.PostAsync("/someurl", content);

The equivalent and a verbose way to do the same using JSON would be the following, which is unnecessary due to the extension method in the first code example:

var httpClient = new HttpClient();
var jsonAsString = "{ \"text\":\"Some text\"}";
var jsonContent = new StringContent(jsonAsString, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("/someurl", jsonContent);

That is it

I hope these examples are useful to you, let me know in the comments if they were or if you need more!