使用.NET Core和C#我尝试向我的Vizio TV发出HTTPS请求时,API有点记录here。
在Chrome中访问HTTP服务器时,我收到了一个" NET :: ERR_CERT_AUTHORITY_INVALID"错误。当我使用HttpClient
在C#中发出请求时,会抛出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");
}
答案 0 :(得分:3)
通过设置HttpClientHandler
并将ServerCertificateCustomValidationCallback
设置为返回true来解决此问题。
using (var handler = new HttpClientHandler {
ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true
})
using (var httpClient = new HttpClient(handler))
答案 1 :(得分:2)
在这里参加聚会为时已晚,但是如果您正在寻找.net核心解决方案,请尝试以下代码
using (var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true })
{
using (var httpClient = new HttpClient(handler))
{
//your business logic goes here
}
}