I needed to set a header while using the HTTPClient in C# for another blog post. I thought this was quite trivial using the GetAsync, PostAsync or PutAsync methods, but it was not. You can set this as a default on your HTTPClient as seen below:
_httpClient.DefaultRequestHeaders.Add("MyFantasticHeader" ,"MyFantasticValue"); var result = await _httpClient.GetAsync( "http://localhost:58116/weatherforecast");
However this sets it for every request you make with this httpClient instance, which is not what I wanted. What I was after was setting the header per request. It does not seem like GetAsync, PostAsync or PutAsync supports this so I ended up using SendAsync instead:
var requestMessage = new HttpRequestMessage(HttpMethod.Get, "http://localhost:58116/weatherforecast"); requestMessage.Headers.Add("MyFantasticHeader", "MyFantasticValue"); var result = await _httpClient.SendAsync(requestMessage);
In the above we send a GET request with the header "MyFantasticHeader" which has the value "MyFantasticValue". SendAsync works differently as it takes a HttpRequestMessage and you have to specify the HTTP method, but in return it gives you full control of the request.
That is all there is to it, let me know in the comments down below if you know a better way or found this helpful! :)