Search code examples
c#dotnet-httpclient

How can we add Header Parameters to HTTPCLIENT object


C# How can we add Header Parameters to HTTPCLIENT object Post-Man Screen-Shot:

A screen shot of POST-MAN which I'm capable of doing there

I have tried the following code snippet as well but, no use.

HttpClient _client = new HttpClient { BaseAddress = new Uri(ServiceBaseURL) };
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_client.DefaultRequestHeaders.TryAddWithoutValidation("Param1", "Value1");
_client.DefaultRequestHeaders.TryAddWithoutValidation("Param2", "Value2");
_client.DefaultRequestHeaders.TryAddWithoutValidation("Param3", "Value3");

Looking forward for help. I really appreciate your help.


Solution

  • I think you want the regular DefaultRequestHeaders property and not the Accept property:

    _client.DefaultRequestHeaders.Add("Param1", "Value1");
    

    You can also add the headers as part of the message (if these parameters change per request use this way instead):

    using (var message = new HttpRequestMessage(HttpMethod.Post, "/someendpoint"))
    {
        message.Headers.Add("Param1", "Value1");
    }