如何解决“ StatusCode:401,ReasonPhrase:“未经授权””错误?

时间:2019-08-08 16:50:57

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

我收到以下错误

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

    }

尽管此处的授权是正确的,但我仍遭到未经授权的

1 个答案:

答案 0 :(得分: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);