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

查看:320
本文介绍了忽略错误的证书-.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天全站免登陆