5

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.

1
  • 1
    Hi Naresh can you please post full code snippet after the solution. I am having same requirement. Commented Apr 23, 2020 at 15:45

2 Answers 2

12

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a mill for your response @maccettura
@nareshmekala if my answer worked for you please mark it as the right answer so other users know what worked.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.