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)
通过设置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)
归档时间: |
|
查看次数: |
3557 次 |
最近记录: |