Ignore bad certificate - .NET CORE(忽略错误的证书 - .NET CORE)
问题描述
我正在编写一个 .NET Core 应用程序来轮询远程服务器并传输显示的数据.这在 PHP 中运行良好,因为 PHP 忽略了证书(这在浏览器中也是一个问题),但我们希望将其移至 C# .NET CORE,因为这是系统中唯一剩下的 PHP.
I'm writing a .NET Core app to poll a remote server and transfer data as it appears. This is working perfectly in PHP because the PHP is ignoring the certificate (which is also a problem in browsers) but we want to move this to C# .NET CORE because this is the only remaining PHP in the system.
我们知道服务器很好,但由于各种原因,证书无法/不会很快更新.
We know the server is good, but for various reasons the certificate can't / won't be updated any time soon.
请求正在使用 HttpClient:
The request is using HttpClient:
HttpClient httpClient = new HttpClient();
try
{
string url = "https://URLGoesHere.php";
MyData md = new MyData(); // this is some data we need to pass as a json
string postBody = JsonConvert.SerializeObject(md);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage wcfResponse = await httpClient.PostAsync(url, new StringContent(postBody, Encoding.UTF8, "application/json"));
Console.WriteLine(wcfResponse.Content);
}
catch (HttpRequestException hre)
{
// This exception is being triggered
}
对此进行研究后,似乎普遍建议使用 ServicePointManager,但这在 .NET Core 中不可用,我无法找到推荐的替代品.
Having researched this it seems the universal recommendation is to use ServicePointManager, but this is not available in .NET Core and I'm having trouble finding the recommended replacement.
在 .NET Core 中是否有一种简单或更好的方法来做到这一点?
Is there a simple or better way to do this in .NET Core?
推荐答案
你想要类似于 new HttpClient()
的东西
Instead of new HttpClient()
you want something akin to
var handler = new System.Net.Http.HttpClientHandler();
using (var httpClient = new System.Net.Http.HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
// Log it, then use the same answer it would have had if we didn't make a callback.
Console.WriteLine(cert);
return errors == SslPolicyErrors.None;
};
...
}
这应该可以在 Windows 和 Linux 上运行,其中 libcurl 被编译为使用 openssl.使用其他 curl 后端,Linux 会抛出异常.
That should work on Windows, and on Linux where libcurl is compiled to use openssl. With other curl backends Linux will throw an exception.
这篇关于忽略错误的证书 - .NET CORE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:忽略错误的证书 - .NET CORE


- C#MongoDB使用Builders查找派生对象 2022-09-04
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01