Reputation: 89
C# How can we add Header Parameters to HTTPCLIENT object Post-Man Screen-Shot:
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.
Upvotes: 5
Views: 23503
Reputation: 89
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
Upvotes: 1
Reputation: 10818
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");
}
Upvotes: 12