【问题标题】:C# How can we add Header Parameters to HTTPCLIENT objectC# 我们如何向 HTTPCLIENT 对象添加标头参数
【发布时间】:2017-04-06 15:12:49
【问题描述】:

C# 我们如何向 HTTPCLIENT 对象添加 Header 参数 邮递员截图:A screen shot of POST-MAN which I'm capable of doing there

下面的代码sn-p我也试过了,没用。

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

期待帮助。非常感谢您的帮助。

再次感谢 nAnI

【问题讨论】:

  • 嗨,Naresh,您能否在解决方案后发布完整的代码 sn-p。我也有同样的要求。

标签: c# api httpclient


【解决方案1】:

我认为您想要常规的 DefaultRequestHeaders 属性而不是 Accept 属性:

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

您还可以将标头添加为消息的一部分(如果这些参数根据请求更改,请改用这种方式):

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

【讨论】:

  • 感谢您的回复@maccettura
  • @nareshmekala 如果我的答案对您有用,请将其标记为正确答案,以便其他用户知道什么有效。
【解决方案2】:

我认为标题参数是我的代码出现问题的根本原因,但事实并非如此。两种方式都适合我

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

再次感谢@maccettura

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-12
    • 2019-09-13
    • 2013-01-29
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    相关资源
    最近更新 更多