C# 如何使用ASP.NET核心验证Web请求的SSL证书

C# 如何使用ASP.NET核心验证Web请求的SSL证书,c#,https,asp.net-core,self-signed,system.net.httpwebrequest,C#,Https,Asp.net Core,Self Signed,System.net.httpwebrequest,我已经使用APS.NET内核(System.NET.HttpWebRequest)实现了一种从RESTAPI请求(基于SSL的请求:https://)获取响应的方法 我需要忽略获取WebResponse时发生的证书错误。我参考了许多博客,找到了使用ServicePointManager的解决方案,并使用了下面的代码 ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, ssl

我已经使用APS.NET内核(
System.NET.HttpWebRequest
)实现了一种从RESTAPI请求(基于SSL的请求:
https://
)获取响应的方法

我需要忽略获取
WebResponse
时发生的证书错误。我参考了许多博客,找到了使用
ServicePointManager
的解决方案,并使用了下面的代码

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; 
但是在ASP.NET核心中,不支持
ServicePointManager
。因此,请帮助我仅通过
HttpWebRequest
解决此问题,而不是通过
HttpClient

解决此问题。NET Core使您可以覆盖代理。例如:

var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
var http = new HttpClient(handler);
Console.WriteLine(http.GetAsync("https://expired.badssl.com/").GetAwaiter().GetResult());
输出:

StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Server: nginx/1.10.0
  Server: (Ubuntu)
  Date: Mon, 06 Mar 2017 05:56:52 GMT
  Transfer-Encoding: chunked
  Connection: keep-alive
  ETag: W/"58924b62-1d5"
  Cache-Control: no-store
  Content-Type: text/html
  Last-Modified: Wed, 01 Feb 2017 20:56:02 GMT
}

在Ubuntu 16.04和.NET 1.0.0-preview2-1-003177上测试。有一个与此相关的问题,在MacOS上也有同样的问题。

在调用请求之前:

ServicePointManager.ServerCertificateValidationCallback = new   
RemoteCertificateValidationCallback(validarCertificado);
…并包括此功能:

protected bool validarCertificado(Object sender,
                              X509Certificate certificado,
                              X509Chain cadena,
                              SslPolicyErrors sslErrores)
{
   return true;
}

我已经提到了这一点。但我想知道如何为HttpWebRequest类实现这一点。例如:
code
stringurl=”“;HttpWebRequest httpRequest=(HttpWebRequest)WebRequest.Create(url);httpRequest.Method=“Get”;httpRequest.ContentType=“application/json”;使用(var result=(HttpWebResponse)(wait Task.Factory.fromsync(httpRequest.BeginGetResponse,httpRequest.EndGetResponse,null)){StreamReader-StreamReader=newstreamreader(result.GetResponseStream());response=streamreadreader.ReadToEnd();}这在.NETCore2.0().HttpWebRequest在.net core中已被弃用,它只是HttpClient上的一个附加层。