【问题标题】:C# How to set Custom request headers using HttpClient in GET Method? [duplicate]C# 如何在 GET 方法中使用 HttpClient 设置自定义请求标头? [复制]
【发布时间】:2019-06-17 23:26:18
【问题描述】:

我正在使用 HttpClient 发送请求,我想在 GET 方法中使用使用 HttpClient 的自定义请求标头?

这是我的代码:

public HttpResponseMessage Get(string url, List<KeyValuePair<string, string>> headers = null)
    {
        HttpRequestMessage request = new HttpRequestMessage()
        {
            RequestUri = new Uri(url),
            Method = HttpMethod.Get,
        };
        if (headers != null && headers.Count > 0)
        {
            foreach (var header in headers)
            {                    
                request.Headers.Add(header.Key, header.Value);

            }
        }            
        HttpResponseMessage response = httpClient.SendAsync(request).Result;
        return response;
    }

但它在request.Headers.Add(header.Key, header.Value); 处抛出了一个错误

以下是错误信息:

错误的标题名称。确保请求标头与 HttpRequestMessage 一起使用,响应标头与 HttpResponseMessage 一起使用,内容标头与 HttpContent 对象一起使用。

任何帮助将不胜感激

【问题讨论】:

  • 你调试代码了吗?遇到异常时,header.Keyheader.Value 中的值是多少?
  • 我的标题是“Content-Type”“application/json”。我在stackoverflow.com/questions/10679214/…找到了解决方法,但它只适用于Http Post方法
  • 对于 GET 请求设置 Content-Type 标头无效。您根本无法为 GET 请求设置 Content-Type 标头。你不应该。
  • @LeeLiu 这不是解决方法,这就是答案。 GET 没有内容,所以使用Content-Type 是一个错误。如果您想请求特定的内容类型,请使用 Accept 标头
  • @ChetanRanpariya 如果我想将客户标头设置为“domain:005”,我该怎么做?

标签: c# http httpclient


【解决方案1】:

您应该使用您的 HttpClient 实例来执行此操作,如下所示:

httpClient.DefaultRequestHeaders
      .Accept
      .Add(new MediaTypeWithQualityHeaderValue("x-your-custom-header"));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 2012-10-03
    • 2017-08-09
    相关资源
    最近更新 更多