本文介绍了HttpClient - 相同的代码在 .NET Framework 和 .NET 5.0 中给出不同的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 .net framework 4.5 项目更新到 .net 5.0,但遇到了问题.经过一番头痛,我发现它是 HttpClient.GetAsync().它根据目标框架给了我不同的例外.

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.

在 .NET Framework 4.5 中,我得到以下异常:(正确的行为)发送请求时发生错误."内部异常请求被中止:无法创建 SSL/TLS 安全通道."

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."

在 .NET 5.0 中,我得到了这个:由于配置的 HttpClient.Timeout 已过 100 秒,请求被取消."内部异常由于线程退出或应用程序请求,I/O 操作已中止."

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."

问题是应用程序在 .NET 5.0 中根本没有响应,而在 .NET Framework 4.5 中它立即抛出异常.

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.

我有以下一段代码:

  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);
  }

请指教,我是 .NET 5.0 的新手.

Please advice, I am new to .NET 5.0.

我已经尝试过AcceptAllCertificates".在 .NET Framework 4.5 中异常会按预期消失,但在 .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.

这种情况下的问题很可能是 VPN 问题.在这种情况下,修复"只是将超时设置为较低的值:

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.

这篇关于HttpClient - 相同的代码在 .NET Framework 和 .NET 5.0 中给出不同的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 07:19