2017-03-06 114 views
0

我已經實現了使用APS.NET核心(System.Net.HttpWebRequest)從REST API請求(基於SSL的請求:https://)獲取響應的方法。如何使用ASP.NET Core驗證Web請求的SSL證書

我需要忽略在獲取WebResponse時發生的證書錯誤。我提到許多博客,並得到使用ServicePointManager的解決方案,用這個下面的代碼

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => true; 

但在ASP.NET核心沒有用於ServicePointManager不支持。所以請幫助我解決這個問題,只能通過HttpWebRequest而不是通過HttpClient

回答

2

.NET Core使ServerCertificateCustomValidationCallback委託可供您覆蓋。例如:

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。有一個open issue與MacOS上的這個工作相同。

+0

我已經提到這一點。但我想知道如何實現這個HttpWebRequest類。 例如: 'code' string url =「https:// XXXXXXXX:XXXX」; HttpWebRequest httpRequest =(HttpWebRequest)WebRequest.Create(url); httpRequest.Method =「Get」; httpRequest.ContentType =「application/json」; 使用(VAR結果=(HttpWebResponse)(AWAIT任務 .Factory.FromAsync(httpRequest.BeginGetResponse,httpRequest.EndGetResponse,NULL))) { 的StreamReader的StreamReader =新的StreamReader(result.GetResponseStream()); response = streamReader.ReadToEnd(); } –

+0

這看起來像是在.NET Core 2.0中可能的(https://github.com/dotnet/corefx/issues/16181)。 – Scovetta

-1

調用請求之前:

ServicePointManager.ServerCertificateValidationCallback = new 
RemoteCertificateValidationCallback(validarCertificado); 

...,包括這樣的功能:

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