首页 > 解决方案 > HttpClient client.GetAsync 可以在完整的 .Net 框架中工作,但不能在 .Net core 2.1 中工作?

问题描述

我有以下代码(需要将 C# 更改为 7.1+ 版)在我的公司网络中运行。它适用于完整的 .Net 框架,但不适用于 .Net core 2.1 应用程序?为什么?(检查 https 站点的证书会显示一些证书是我公司颁发的)

public static async Task Main(string[] args)
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    var client = new HttpClient();
    var response = await client.GetAsync("https://usbtrustgateway.usbank.com/portal/");
    response.EnsureSuccessStatusCode();
    var content = await response.Content.ReadAsStringAsync();
    Console.WriteLine(content);
}

client.GetAsync(...)它在.Net核心的行上得到以下异常

抛出异常:System.Private.CoreLib.dll 中的“System.Net.Http.HttpRequestException”(“无法建立 SSL 连接,请参阅内部异常。”)抛出异常:系统中的“System.Net.Http.HttpRequestException” .Private.CoreLib.dll(“无法建立 SSL 连接,请参阅内部异常。”)超链接:激活历史调试 0.95 秒 [15948] 工作线程

内部异常是

现有连接被远程主机强行关闭

标签: c#.net.net-corehttpclient

解决方案


我已经关注这个帖子一段时间了,我很好奇关注是否会解决它。我们在 .Net Core 中遇到了类似的问题。

在您的 appsettings.json 中,尝试添加...

“DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER”:“0”

例子:

"profiles": {
"IIS Express": {
  "commandName": "IISExpress",
  "launchBrowser": true,
  "launchUrl": "https://localhost:44349/",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development",
    "DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER": "0"
  }
},

推荐阅读