【发布时间】:2018-09-23 21:44:02
【问题描述】:
我需要从我的 WebAPI 控制器内部的 API 端点获取数据。我正在使用HttpClient 来实现目标。但是,客户端似乎无法从端点获取数据。 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>
API 端点使用有效的 SSL 证书正确托管。此外,如果我使用控制台应用程序/使用邮递员访问 API,则没有错误,我可以看到响应。但是,当我尝试从 API 控制器内部以完全相同的方式访问相同的 API 时,我看到 SSL 连接错误。
这是客户端的代码:
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);
为什么来自 WebAPI 的 connect 请求的行为与控制台应用程序不同?你能帮我解决上面的问题吗?
【问题讨论】:
-
您在控制台和 Web api 中的目标是什么版本的 .NET 框架?旧版本默认使用旧版本的 TLS,这可能会被端点拒绝。您可以手动设置与 servicepointmanager.securityprotocol 一起使用的协议
-
谢谢!我将我的框架从 4.5 升级到 4.6.2 并升级了我的所有软件包以使其工作!顺便说一句,即使设置 TLS 版本对我来说也不起作用。请将此作为答案发布。
标签: c# httpclient