.NET Core HttpClient-“发生安全错误” HttpRequestException

Aus*_*ngs 4 c# ssl https .net-core

我正在使用.NET Core和C#尝试向Vizio TV发出HTTPS请求,该API 在此处有所记录。

在Chrome浏览器中访问HTTP服务器时,出现“ NET :: ERR_CERT_AUTHORITY_INVALID”错误。当我在C#中使用a发出请求时HttpClient,将HttpRequestException引发a。我曾尝试将证书添加到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");
}
Run Code Online (Sandbox Code Playgroud)

Aus*_*ngs 5

通过设置HttpClientHandler和设置ServerCertificateCustomValidationCallback为返回true来解决此问题。

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

  • 只是想表明导致异常的根本原因可能是无效的证书,并且您实际上是在此处禁用证书检查。您不应该在生产代码中执行此操作! (3认同)