gpt4 book ai didi

c# - .NET 核心 HttpClient - "A security error occurred"HttpRequestException

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:31 24 4
gpt4 key购买 nike

我正在尝试使用 .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");
}

最佳答案

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

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

关于c# - .NET 核心 HttpClient - "A security error occurred"HttpRequestException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49351595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com