C# - How to add or remove headers using the HttpClient

You can set default headers on the HttpClient using the DefaultRequestHeaders property:

_httpClient.DefaultRequestHeaders.Add("MyFantasticHeader"
   ,"MyFantasticValue");
var result = await _httpClient.GetAsync(
   "http://localhost:58116/weatherforecast");

Whatever request you make with the HttpClient it will include that header, whether it is a GetAsync, PostAsync or PutAsync method. You can remove the header by using the Remove method:

_httpClient.DefaultRequestHeaders.Remove("MyFantasticHeader");

This sets this header for all requests from that HttpClient, keep reading if you want it per request.

Setting headers per request

You may not want to set the headers for every request but rather per request. It can be hard to figure out what headers are set on a given request if you reuse your httpclient throughout your application. Therefore you may want to set them per request rather than as default headers. An example of this can be seen below:

var requestMessage = new HttpRequestMessage(HttpMethod.Get, 
   "http://localhost:58116/weatherforecast");
requestMessage.Headers.Add("MyFantasticHeader", 
   "MyFantasticValue");
var result = await _httpClient.SendAsync(requestMessage);

You will have to use the HttpRequestMessage object as there are no overloads for GetAsync, PostAsync or PutAsync to take specific headers. The Headers collections on the HttpRequestMessage works the same as DefaultRequestHeaders and you can remove headers by calling the Remove method:

requestMessage.Headers.Remove("MyFantasticHeader");

That is all

I hope you found this useful, please leave a comment down below! I read all of them.