【问题标题】:.NET Core HttpClient - "A security error occurred" HttpRequestException.NET Core HttpClient - “发生安全错误” HttpRequestException
【发布时间】:2018-08-27 08:12:22
【问题描述】:

我正在尝试使用 .NET Core 和 C# 向我的 Vizio TV 发出 HTTPS 请求,API 有一些记录在 here。

在 Chrome 中访问 HTTP 服务器时,我收到“NET::ERR_CERT_AUTHORITY_INVALID”错误。当我在 C# 中使用 HttpClient 发出请求时,会抛出 HttpRequestException。我尝试将证书添加到 Windows,但我对 TLS 还不够熟悉。

我也不担心我的通信被窥探,所以我想忽略任何 HTTPS 错误。

这是我正在使用的相关代码。

public async Task Pair(string deviceName) {
    using (var httpClient = new HttpClient())
    try {
        httpClient.BaseAddress = new Uri($"https://{televisionIPAddress}:9000/");

        // Assume all certificates are valid?
        ServicePointManager.ServerCertificateValidationCallback =
            (sender, certificate, chain, sslPolicyErrors) => true;

        deviceID = Guid.NewGuid().ToString();

        var startPairingRequest = new HttpRequestMessage(HttpMethod.Put, "/pairing/start");
        startPairingRequest.Content = CreateStringContent(new PairingStartRequestBody {
            DeviceID = deviceID,
            DeviceName = deviceName
        });

        var startPairingResponse = await httpClient.SendAsync(startPairingRequest); // HttpRequestException thrown here
        Console.WriteLine(startPairingResponse);
    } catch (HttpRequestException e) {
        Console.WriteLine(e.InnerException.Message); // prints "A security error occurred"
    }
}

StringContent CreateStringContent(object obj) {
    return new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
}

【问题讨论】:

    标签: c# ssl https .net-core


    【解决方案1】:

    在这里聚会为时已晚,但如果您正在寻找 .net 核心解决方案,请尝试以下代码

    using (var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true })
            {
                using (var httpClient = new HttpClient(handler))
                {
                    //your business logic goes here
                }
            }
    

    【讨论】:

      【解决方案2】:

      通过设置HttpClientHandler 并将ServerCertificateCustomValidationCallback 设置为返回true 解决了该问题。

      using (var handler = new HttpClientHandler {
          ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
      })
      using (var httpClient = new HttpClient(handler))
      

      【讨论】:

      • 只是想指出异常的根本原因可能是无效的证书,并且您在此处有效地禁用了证书检查。你不应该在生产代码中这样做!
      猜你喜欢
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 2018-02-13
      • 1970-01-01
      • 2019-12-25
      • 2020-01-26
      相关资源
      最近更新 更多