Custom header to HttpClient request

273,698

Solution 1

var request = new HttpRequestMessage {
    RequestUri = new Uri("[your request url string]"),
    Method = HttpMethod.Post,
    Headers = {
        { "X-Version", "1" } // HERE IS HOW TO ADD HEADERS,
        { HttpRequestHeader.Authorization.ToString(), "[your authorization token]" },
        { HttpRequestHeader.ContentType.ToString(), "multipart/mixed" },//use this content type if you want to send more than one content type
    },
    Content = new MultipartContent { // Just example of request sending multipart request
        new ObjectContent<[YOUR JSON OBJECT TYPE]>(
            new [YOUR JSON OBJECT TYPE INSTANCE](...){...}, 
            new JsonMediaTypeFormatter(), 
            "application/json"), // this will add 'Content-Type' header for the first part of request
        new ByteArrayContent([BINARY DATA]) {
            Headers = { // this will add headers for the second part of request
                { "Content-Type", "application/Executable" },
                { "Content-Disposition", "form-data; filename=\"test.pdf\"" },
            },
        },
    },
};

Solution 2

I have found the answer to my question.

client.DefaultRequestHeaders.Add("X-Version","1");

That should add a custom header to your request

Solution 3

Here is an answer based on that by Anubis (which is a better approach as it doesn't modify the headers for every request) but which is more equivalent to the code in the original question:

using Newtonsoft.Json;
...

var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        RequestUri = new Uri("https://api.clickatell.com/rest/message"),
        Headers = { 
            { HttpRequestHeader.Authorization.ToString(), "Bearer xxxxxxxxxxxxxxxxxxx" },
            { HttpRequestHeader.Accept.ToString(), "application/json" },
            { "X-Version", "1" }
        },
        Content = new StringContent(JsonConvert.SerializeObject(svm))
    };

var response = client.SendAsync(httpRequestMessage).Result;

Solution 4

There is a Headers property in the HttpRequestMessage class. You can add custom headers there, which will be sent with each HTTP request. The DefaultRequestHeaders in the HttpClient class, on the other hand, sets headers to be sent with each request sent using that client object, hence the name Default Request Headers.

Hope this makes things more clear, at least for someone seeing this answer in future.

Solution 5

I have added x-api-version in HttpClient headers as below :

var client = new HttpClient(httpClientHandler)
{
    BaseAddress = new Uri(callingUrl)
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("x-api-version", v2);
Share:
273,698

Related videos on Youtube

Libin Joseph
Author by

Libin Joseph

Founder: Xhackers Kerala

Updated on July 08, 2022

Comments

  • Libin Joseph
    Libin Joseph almost 2 years

    How do I add a custom header to a HttpClient request? I am using PostAsJsonAsync method to post the JSON. The custom header that I would need to be added is

    "X-Version: 1"
    

    This is what I have done so far:

    using (var client = new HttpClient()) {
        client.BaseAddress = new Uri("https://api.clickatell.com/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "xxxxxxxxxxxxxxxxxxxx");
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var response = client.PostAsJsonAsync("rest/message", svm).Result;
    }
    
  • Ruhrpottpatriot
    Ruhrpottpatriot almost 7 years
    No, it does not. This answer should be viewed with caution, since the defaults request headers are sent with each request. You should build your request like @Anubis suggested. DefaultsRequestHeaders should be populated when you create the HttpClient.
  • kamilk
    kamilk over 5 years
    This only works because you are instantiating a new HttpClient for every request. This is not the way this class should be used: it should be a static field, reused for all requests, at least those to the same endpoint. See documentation and countless blog posts out there. Then, as of course, as @Ruhrpottpatriot points out, changing default headers will affect all requests.
  • heug
    heug over 5 years
    answer is extremely confusing ... why are you bringing in code for documents, blank.pdf, etc? instantiating bytearray classes to pass custom headers within the Content param?
  • Anubis
    Anubis over 5 years
    @heug Well. If you are looking for header you can see it. Content is present here in order to complete the picture because you most likely want to add some content to your request. And in order to not be tedious the content is complicated and contain both JSON and binary data.
  • heug
    heug over 5 years
    it just seems more straightfoward to do it like this: create StringContent using your content JSON, create a HTTP message with your method and URI, then add headers like message.Headers.Add("x":"y") .... then pass those into a response var like "var response = await httpClient.SendAsync(message);"
  • Anubis
    Anubis over 5 years
    @heug I will remember this for the furute. Thanks!
  • joedotnot
    joedotnot over 5 years
    No, does not make it any clearer. In both cases you are saying you are sending headers on every request - So what is the difference?
  • Ross Presser
    Ross Presser about 5 years
    Headers is a property of an individual HttpRequestMessage object. Thus you can create different messages with different headers. DefaultRequestHeaders is a property of the HttpClient object; if multiple messages are sent through a given HttpClient, all such messages will all have the same DefaultRequestHeaders added to the message's individual headers.
  • Panagiotis Kanavos
    Panagiotis Kanavos about 5 years
    @RossPresser definitely not. Content-Type is a Content header.
  • Ron
    Ron about 5 years
    Which line in the above accepted answer actually implements the header that the OP requested, X-Version? Why is this considered the accepted answer?
  • Ron
    Ron about 5 years
    Agreed this is the answer. It demonstrates how to add the header that OP requested. Answered my question as well.
  • David Klempfner
    David Klempfner about 5 years
    @Ruhrpottpatriot What's wrong with sending the header for every request?
  • Ruhrpottpatriot
    Ruhrpottpatriot about 5 years
    @Backwards_Dave See the comment directly above yours
  • ajbeaven
    ajbeaven about 5 years
    @kamilk Microsoft's docs specifically recommend disposing the HttpClient after each use, so there's nothing wrong with this. docs.microsoft.com/en-us/dotnet/api/…
  • kamilk
    kamilk about 5 years
    @ajbeaven Nope, that's not what it says. The example at the top of the page shows the Main method of the app, so even though the HttpClient is disposed of, the same instance is used throughout the lifetime of the application, and that is correct in regards to what the documentation says a little bit further down: 'HttpClient is intended to be instantiated once and re-used throughout the life of an application'. Following this paragraph is an example recommending assigning an HttpClient to a static field.
  • ajbeaven
    ajbeaven about 5 years
    @kamilk, you're dead right - that example put me wrong. Thanks for putting me right :)
  • Tom Anderson
    Tom Anderson over 4 years
    Adding a header to the default headers does not instantiate a new HttpClient, it merely adds another header. To remove the header, use client.DefaultRequestHeaders.Remove("X-Version"); (or client.DefaultRequestHeaders.Clear() to remove all).
  • Mass Dot Net
    Mass Dot Net over 4 years
    FYI I think HttpRequestHeader.Access should be HttpRequestHeader.Accept.
  • aswzen
    aswzen over 4 years
    what is svm by the way?
  • Chris Peacock
    Chris Peacock over 4 years
    @aswzen It's from the OP's question - something model I would guess. The object being serialised.
  • Anubis
    Anubis about 4 years
    Sorry. I had to prittify my answer long ago. Hope it is less confusing now.
  • FARHAD AFSAR
    FARHAD AFSAR almost 4 years
    really why? why making a HTTP request with c# has to be more difficult than c or more difficult than do it with a simple TCP socket? all this headers will gather in payload as simple string and lines, so i think this much of classes and abstracts are just waste of time.
  • Kzrbill
    Kzrbill over 3 years
    Use DefaultRequestHeaders for your app's "global" instance of HttpClient only. "HttpClient is intended to be instantiated once per application" docs.microsoft.com/en-us/dotnet/api/…. Better to use HttpRequestMessage as described in @Chris Peacock's answer above for granular customisation of specific http request. Both approaches are valid its just HttpRequestMessage gives better control without adverse side effects to other consumers of you client unless DefaultRequestHeaders are really intended to be just that.
  • Jerameel Resco
    Jerameel Resco about 3 years
    Using the code snippet Chris Peacock provided works for me. The same question scenario I had with the OP. Used the HttpRequestMessage class as well and the SendAsync() method.
  • Alex
    Alex about 3 years
    +1 But still you shouldn't create new HttpClient-instances for every request, this answer could misdirect users in that aspect.
  • Chris Peacock
    Chris Peacock about 3 years
    @Alex yes, agreed. This was just supposed to be a self-contained example that related easily to the OP's question.
  • Psddp
    Psddp almost 3 years
    Since DefaultRequestHeaders is not thread safe, you shouldn't use it if you care about paralellism: docs.microsoft.com/en-us/dotnet/api/…
  • Saad Khan
    Saad Khan almost 3 years
    It is mentioned in the documentation that you should instantiate HTTPClient only once per application and should not create a new instance for every request. What is the reason for this recommendation? What is the disadvantage?
  • Alex from Jitbit
    Alex from Jitbit over 2 years
    Is is ok to use this answer if you're instantiating httpclient using HttpClientFactory?
  • Alex from Jitbit
    Alex from Jitbit over 2 years
    I found this answer really helpful, thanks for the extra examples.