简体   繁体   中英

HttpClient - same code gives different exceptions in .NET Framework and .NET 5.0

I am trying to update a .net framework 4.5 project to .net 5.0, but ran into a problem. After some headache I found it to be HttpClient.GetAsync(). It gives me different exceptions depending on the target framework.

In .NET Framework 4.5 I get the following exception: (Correct behaviour) "An error occurred while sending the request." with the inner exception "The request was aborted: Could not create SSL/TLS secure channel."

While in .NET 5.0 I get this: "The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing." with the inner exception "The I/O operation has been aborted because of either a thread exit or an application request."

The problem is that the application get no response at all in .NET 5.0, while in .NET Framework 4.5 it immediately throws the exception.

I have the following piece of code:

  string deviceAddress = "https://192.168.1.173:443";
  HttpClientHandler httpClientHandler = new HttpClientHandler();
  HttpClient httpClient = new HttpClient(httpClientHandler);
  Uri uri = new Uri(deviceAddress);

  try
  {
    HttpResponseMessage response = await httpClient.GetAsync(uri);
  }
  catch (Exception ex)
  {
    Debug.WriteLine(ex.Message);
  }

Please advice, I am new to .NET 5.0.

I have tried the 'AcceptAllCertificates'. In .NET Framework 4.5 the exception disappears as expected, but in .NET 5.0 there are no difference, the function never gets called.

httpClientHandler.ServerCertificateCustomValidationCallback = AcceptAllCertificates; 

protected bool AcceptAllCertificates(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
  return true;
}

I answer my own question after some more hacking around, and hope it helps someone.

The problem in this case is most probably a VPN-issue. The 'fix' in this case was simply to set the Timeout to a low value:

httpClient.Timeout = TimeSpan.FromSeconds(4.0);

This way I get the timeout-exception instead, after an acceptable amount of time. This is of course not the solution but a workaround.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM