【问题标题】:StatusCode 401 Reason Unauthorized when calling PostAsync WebRequest调用 PostAsync WebRequest 时,StatusCode 401 原因未经授权
【发布时间】:2017-04-28 15:49:52
【问题描述】:

我是 C# HttpClient 类的新手,我希望你们可以帮助我解决我的问题。尝试调用 PostAsync 方法时收到 StatusCode 401。这是我的代码

public WebClient(HttpClient httpClient)
    {
        string webHost = ConfigurationManager.AppSettings["webHost"];
        string webApiKey = ConfigurationManager.AppSettings["webApikey"];

        _httpClient = httpClient;
        _httpClient.BaseAddress = new Uri(webHost);
        _httpClient.DefaultRequestHeaders.Accept.Clear();
        _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("x-coupa-api-key", "=" + ConfigurationManager.AppSettings["coupaApikey"]);
        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
    }

public Tuple<bool, Task<HttpResponseMessage>> Comment(comment comment)
    {
        try
        {
            string commentUrl = string.Format("{0}api/comments/", _webHost);
            var responseMessage = _httpClient.PostAsync(commentUrl, CreateHttpContent(comment));
            Log.Error("Response message: " + responseMessage.Result);
            return new Tuple<bool, Task<HttpResponseMessage>>(responseMessage.Result.IsSuccessStatusCode, responseMessage);

        }
        catch (Exception ex)
        {
            Log.Error("Call to Web failed.", ex);
            throw;
        }

    }

private static HttpContent CreateHttpContent(comment data)
    {
        var format = "application/xml";

        return new StringContent(Common.SerializeUtf8(data), Encoding.UTF8, format);
    }

所以我将带有 POST 的 xml 发送到网络主机 - 我从 PostAsync 获得以下结果:

响应消息:

StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Transfer-Encoding: chunked
  Status: 401 Unauthorized
  X-Frame-Options: SAMEORIGIN
  X-XSS-Protection: 1; mode=block
  X-Content-Type-Options: nosniff
  X-Request-Id: 53e17930-f9fe-4ec4-ae5b-b772ce5f308e
  X-Runtime: 0.025822
  Cache-Control: no-cache
  Date: Wed, 26 Apr 2017 06:07:39 GMT
  Content-Type: text/html
}

【问题讨论】:

    标签: c# http-headers httpclient http-status-code-401


    【解决方案1】:

    找到了解决方案。不应该使用授权,只是“添加标题”:

    _httpClient.DefaultRequestHeaders.Add("x-coupa-api-key", ConfigurationManager.AppSettings["webApikey"]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 2011-03-06
      • 2018-05-19
      相关资源
      最近更新 更多