12

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

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Please don't add taglines to your posts. The place for those is in your user profile.
I think the question is about HttpClient and not HttpWebRequest. Answer from @fabricio-koch is correct.
4

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;
}

1 Comment

This will only work for default request headers. It will not work for custom headers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.