HttpClient client.GetAsync works in full .Net fram

2019-08-21 14:30发布

I have the following code (need to change C# to version 7.1+) running in my company network. It works in full .Net framework but not in .Net core 2.1 application? Why? (Checking the Certificate of the https sites will show some of the certificates are issued by my company)

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

It gets the following exception on the line client.GetAsync(...) in .Net core

Exception thrown: 'System.Net.Http.HttpRequestException' in System.Private.CoreLib.dll ("The SSL connection could not be established, see inner exception.") Exception thrown: 'System.Net.Http.HttpRequestException' in System.Private.CoreLib.dll ("The SSL connection could not be established, see inner exception.") Hyperlink: Activate Historical Debugging 0.95s [15948] Worker Thread

The inner exception is

An existing connection was forcibly closed by the remote host

1条回答
欢心
2楼-- · 2019-08-21 15:05

I've been following this thread for a while, and I'm curious if the follow will fix it. We ran into a similar issue with .Net Core.

In your appsettings.json, try adding...

"DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER": "0"

Example:

"profiles": {
"IIS Express": {
  "commandName": "IISExpress",
  "launchBrowser": true,
  "launchUrl": "https://localhost:44349/",
  "environmentVariables": {
    "ASPNETCORE_ENVIRONMENT": "Development",
    "DOTNET_SYSTEM_NET_HTTP_USESOCKETSHTTPHANDLER": "0"
  }
},
查看更多
登录 后发表回答