I am developing simple Http client to consume an Asp.Net Core Web API. I want to pass few http header values to the Web API via HttpHeaderCollection. In previous versions of .Net framework allowed to add header values to the HttpHeaderCollection as following
WebHeaderCollection aPIHeaderValues = new WebHeaderCollection();
aPIHeaderValues .Add("UserName","somevalue");
aPIHeaderValues .Add("TokenValue", "somevalue");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.add(aPIHeaderValues);
HttpWebResponse response = (HttpWebResponse)_request.GetResponse();
But in .Net Core there is no way to add headers to request.Headers collection. As well as we cannot add headers by defining new WebHeaderCollection
WebHeaderCollection aPIHeaderValues = new WebHeaderCollection();
Is there any alternative way to do this in .Net Core
Add Custom Headers to ASP.NET Core Response Using HTTPClientFactory to Add header If you are using HTTPClientFactory based HttpClient, you can send Custom headers in the request using Named HTTPClient or Typed HTTPClient. The below example shows, we can use the DefaultRequestHeaders property to define the headers while using HTTPClientFactory.
Below discussed approach, you can very much use it for .NET Core 3.1 or .NET 5 or 6 version. Using HTTPClient DefaultRequestHeaders to add headers. If you are looking to add a custom header to a Response then please refer to the below article, If you are using HTTPClientFactory based HttpClient, you can send Custom headers in the request using
To add a Authorization Header var request = new HttpRequestMessage () { Headers = { Accept = { new MediaTypeWithQualityHeaderValue ("application/json") }, AcceptEncoding = { new StringWithQualityHeaderValue ("gzip")}, Authorization = new AuthenticationHeaderValue ("Bearer", "") }, RequestUri = new Uri (gatewayUrl), Method = httpMethod, };
When you want to set the Accept type and content type, just cast the webrequest to HttpwebRequest Show activity on this post. You need to be sure that you type cast the request to (HttpWebRequest), where the accept header property is available. In the old WebRequest class, the Accept header is not accessible.
The question is about HttpWebRequest
, which is different than HttpClient
.
Using HttpWebRequest
, you simply assign to a header you want like this:
request.Headers["HeaderToken"] = "HeaderValue";
.NET core will create the header if it does not exist.
Here is an example:
SampleClass sampleClass= null;
using (HttpClient client = new HttpClient()){
client.DefaultRequestHeaders.Add("Authorization", "TOKEN");
var data = await client.GetAsync("MY_API_URL");
var jsonResponse = await data.Content.ReadAsStringAsync();
if (jsonResponse != null)
sampleClass= JsonConvert.DeserializeObject<SampleClass>(jsonResponse);
return sampleClass;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With