Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How can we add Header Parameters to HTTPCLIENT object

Tags:

c#

api

httpclient

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.

Thanks Again nAnI

like image 729
Naresh Avatar asked Dec 23 '22 19:12

Naresh


2 Answers

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");
}
like image 159
maccettura Avatar answered Dec 28 '22 06:12

maccettura


I thought header parameters are the root cause for an issue with my code which is not. Either the ways worked for me

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

Thanks Again @maccettura

like image 42
Naresh Avatar answered Dec 28 '22 06:12

Naresh