2

I had implemented a method for getting the response from a REST API request(SSL based one : https://) using APS.NET core (System.Net.HttpWebRequest).

I need to ignore the certificate error which occurred while getting the WebResponse. I referred many blogs and got a solution of using ServicePointManager and used this below code

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

But in ASP.NET core there is no support for ServicePointManager. So please help me to resolve this issue only by means of HttpWebRequest not by means of HttpClient.

Nico
  • 12,493
  • 5
  • 42
  • 62
Clinton Prakash
  • 967
  • 9
  • 20

2 Answers2

4

.NET Core makes the ServerCertificateCustomValidationCallback delegate available for you to override. Example:

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

Output:

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
}

Tested on Ubuntu 16.04 with .NET 1.0.0-preview2-1-003177. There is an open issue related to this working the same on MacOS.

Scovetta
  • 3,112
  • 1
  • 14
  • 13
  • I had already referred this. But I want to know how to implement this for HttpWebRequest class. For example: `code` string url="https://XXXXXXXX:XXXX"; HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url); httpRequest.Method = "Get"; httpRequest.ContentType = "application/json"; using (var result = (HttpWebResponse)(await Task.Factory.FromAsync(httpRequest.BeginGetResponse, httpRequest.EndGetResponse, null))) { StreamReader streamReader = new StreamReader(result.GetResponseStream()); response = streamReader.ReadToEnd(); } – Clinton Prakash Mar 08 '17 at 07:19
  • This looks like it will be possible in .NET Core 2.0 (https://github.com/dotnet/corefx/issues/16181). – Scovetta Mar 10 '17 at 06:13
  • 1
    HttpWebRequest is deprecated in .net core and just an additional layer on top of HttpClient. – Cyprien Autexier Jun 16 '18 at 12:16
-1

Before calling the request:

ServicePointManager.ServerCertificateValidationCallback = new   
RemoteCertificateValidationCallback(validarCertificado);

...And include this function:

protected bool validarCertificado(Object sender,
                              X509Certificate certificado,
                              X509Chain cadena,
                              SslPolicyErrors sslErrores)
{
   return true;
}
CDspace
  • 2,639
  • 18
  • 30
  • 36