简体   繁体   English

HttpClient无法与HTTPs端点握手

[英]HttpClient unable to handshake with an HTTPs endpoint

I have a requirement to get data from an API endpoint from inside my WebAPI controller. 我需要从WebAPI控制器内部的API端点获取数据。 I am using HttpClient to achieve the goal. 我正在使用HttpClient实现目标。 However, it seems the client is unable to fetch data from the endpoint. 但是,客户端似乎无法从端点获取数据。 The connect call fails with the below error: connect调用失败,并显示以下错误:

 HTTPS handshake to test.site failed. System.IO.IOException Unable to read  
 data from the transport connection: An existing connection was forcibly  
 closed by the remote host. <An existing connection was forcibly closed by 
 the remote host>

The API endpoint is hosted properly with a valid SSL cert. 使用有效的SSL证书正确托管API端点。 Moreover, if I use a console app / use postman to hit the API, there is no error and I can see the response. 此外,如果我使用控制台应用程序/使用邮递员访问API,则没有错误,并且可以看到响应。 However, when I try to hit the same API in exactly the same manner from inside my API controller, I see the SSL connection error. 但是,当我尝试从API控制器内部以完全相同的方式访问相同的API时,会看到SSL连接错误。

Here's the code for the client: 这是客户端的代码:

HttpClient client = new HttpClient()
        {
            BaseAddress = new Uri(uri)
        };

var requestMessage = new HttpRequestMessage(                                
                         new HttpMethod("GET"),
                         requestUrl);

ServicePointManager.ServerCertificateValidationCallback += 
                                (sender, certificate, chain, sslPolicyErrors) => true;

client.DefaultRequestHeaders.Add(
                "User-Agent",
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

var responseMessage = await client.SendAsync(requestMessage);

Why is the behavior different for the connect request from the WebAPI as compared to a console app? 与控制台应用程序相比,为什么WebAPI发出的connect请求的行为不同? Can you help me fix the above issue? 您能帮我解决以上问题吗?

Older versions of the .NET framework default to using older versions of TLS which may get rejected by the endpoint. .NET框架的较旧版本默认使用较旧的TLS,而TLS可能会被端点拒绝。 It is becoming standard to reject requestd using less than TLS v1.2. 拒绝使用低于TLS v1.2的请求已成为标准。

To get around this you can either use a newer version of the .NET framework or you may be able to explicitly set which version(s) of TLS the ServicePointManager uses. 要解决此问题,您可以使用.NET框架的较新版本,也可以显式设置ServicePointManager使用的TLS版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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