简体   繁体   English

C#如何将标头参数添加到HTTPCLIENT对象

[英]C# 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 C#如何将标头参数添加到HTTPCLIENT对象Post-Man Screen-Shot: 我可以在其中执行POST-MAN的屏幕截图

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 再次感谢

I think you want the regular DefaultRequestHeaders property and not the Accept property: 我认为您需要常规的DefaultRequestHeaders属性,而不是Accept属性:

_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");
}

I thought header parameters are the root cause for 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 再次感谢@maccettura

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM