【问题标题】:How to fix "StatusCode: 401, ReasonPhrase: 'Unauthorized'" error? [duplicate]如何修复“StatusCode:401,ReasonPhrase:'未授权'”错误? [复制]
【发布时间】:2019-08-08 16:50:57
【问题描述】:

我收到以下错误

{StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Transfer-Encoding: chunked
  Date: Mon, 05 Aug 2019 19:38:00 GMT
  Server: Kestrel
  X-Powered-By: ASP.NET
}}

这是我使用的代码

  static void Main(string[] args)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var paras = new Dictionary<string, string>
        {
            {"Authorization", "042a9ff198c04caf99161406f46e|API Testing"},
            {"Content-Type", "application/json"}
        };

        var response = client.PostAsync("https://tsrvcis/cis-api/get-jrsc?format=json", new FormUrlEncodedContent(paras)).Result;
        Debug.WriteLine(response);

    }

虽然这里的授权是正确的,但我仍然未经授权。

【问题讨论】:

    标签: c# asp.net .net asp.net-mvc .net-core


    【解决方案1】:

    如果访问您的服务器通常需要登录,那么您可能想尝试将 NetworkCredentials 与您的 HttpClient 一起使用。

            var httpClientHandler = new HttpClientHandler()
            {
                Credentials = new NetworkCredential(username, password, domainName),
            };
    
            var httpClient = new HttpClient(httpClientHandler);
            // This is 10 seconds.
            httpClient.Timeout = new TimeSpan(100000000);
            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
            // Serialize the object
            var serializedItem = new StringContent(
                JsonConvert.SerializeObject(myUnserializedObject),
                Encoding.UTF8, 
                "application/json");
    
            var result = await httpClient.PostAsync(url, serializedItem);
    

    【讨论】:

      猜你喜欢
      • 2020-12-09
      • 1970-01-01
      • 2016-01-26
      • 2021-03-27
      • 1970-01-01
      • 1970-01-01
      • 2019-12-03
      • 2021-08-31
      • 1970-01-01
      相关资源
      最近更新 更多