C# HttpClient An existing connection was forcibly closed by the remote host

后端 未结 5 936
一生所求
一生所求 2020-12-15 02:37

I\'m working on an integration with Alternative Payments using their hosted page integration. Their C# SDK does not have this integration available at the moment, but as you

相关标签:
5条回答
  • 2020-12-15 03:14

    I don't see in your code sample where you are setting the value of _baseUrl, but I'm assuming that is being done somewhere. I'm also assuming that since this related to payments, the URL is HTTPS. If the remote host has disabled TLS 1.0 and your connection is coming in as TLS 1.0, it could cause that behavior. I know C# 4.6 has TLS 1.0/1.1/1.2 support enabled by default, but I think C# 4.6 still defaults to only SSL3/TLS 1.0 even though TLS 1.1 and 1.2 are supported. If this is the cause of the issue, you can manually add TLS 1.1 and 1.2 to the enabled values using the following code.

    System.Net.ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
    
    0 讨论(0)
  • 2020-12-15 03:15

    For me this error was caused by forgetting to configure the proxy server. Using the following code to construct the HttpClient solved it for my .NET 4.7.2 application:

    var httpClientHandler = new HttpClientHandler { Proxy = WebRequest.GetSystemWebProxy() };
    var httpClient = new HttpClient(httpClientHandler);
    

    Hope this helps someone.

    0 讨论(0)
  • 2020-12-15 03:16

    This worked for me, the first line ensures the protocols ssl3 and TLS1.2, and the second line ignores any potential certificate errors (ignore and continue - like expired certs.):

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
    ServicePointManager.ServerCertificateValidationCallback +=  (sender, certificate, chain, sslPolicyErrors) => true;
    
    0 讨论(0)
  • 2020-12-15 03:17

    If you are using .Net 4.0 then SecurityProtocolType.Tls11 and SecurityProtocolType.Tls2 are not defined so instead you can use the hard coded value below.

    ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

    0 讨论(0)
  • 2020-12-15 03:28

    It is possible to solve the issue without any changes in the code, as described in this excellent answer to a similar question:

    Retarget the web project to .Net 4.6+, then update web.config as the following:

    <system.web>
      <compilation targetFramework="4.6" /> 
      <httpRuntime targetFramework="4.6" /> 
    </system.web>
    
    0 讨论(0)
提交回复
热议问题