忽略错误证书 - .NET CORE [英] Ignore bad certificate - .NET CORE

查看:53
本文介绍了忽略错误证书 - .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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆