【发布时间】:2018-11-16 12:52:25
【问题描述】:
一般来说,我是网络新手。不知道这里有什么问题。
我有一台带有 IIS 的机器,在 https 上运行 ASP NET Core REST API。 我可以通过执行以下任一操作来确认 GET 在我的机器上通过 Google Chrome 运行
- https://test-machine/api/Example(工作)
- https://10.0.0.21/api/Example(证书无效,请注意这是预期的,因为证书适用于“测试机”)
我确认 POST 操作正在使用 Postman(再次忽略无效证书)。 在我尝试编写客户端应用程序之前,一切都很好。
我有以下代码。
var ip = Dns.GetHostAddresses("test-machine");
// ip contains the correct IP
using (var hc = new HttpClient())
{
hc.GetAsync(@"https://test-machine/api/Example").Wait();
}
此代码失败。我得到一个 System.AggregateException:“发生了一个或多个错误。”有 4 个例外叠加在一起。
- HttpRequestException:发送请求时出错。
- WebException:底层连接已关闭:发送时发生意外错误。
- IOException:无法从传输连接读取数据:现有连接被远程主机强行关闭。
- SocketException:现有连接被远程主机强行关闭
如果我将代码更改为使用 IP:
using (var hc = new HttpClient())
{
hc.GetAsync(@"https://10.0.0.21/api/Example").Wait();
}
然后请求按预期工作,即与 Chrome 一样,我遇到了证书问题:
AuthenticationException:根据验证程序,远程证书无效。
我做错了什么? Dns 显然能够获得正确的 IP,我在 GetHostAddresses 返回的 IPAddress[] 中看到了它。为什么 HttpClient 没有解析 IP - 或者它正在解决另一个问题的 IP?
我试过了
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
和
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
但这没有区别。使用
ServicePointManager.ServerCertificateValidationCallback
也不起作用,因为它永远不会到达调用回调的地步。在那之前就失败了。
我怀疑问题是因为我不熟悉这些东西,所以我在某个地方遗漏了一些重要的东西。
我还要注意 - 这是一个 .net 4.5.2 控制台应用程序。我尝试迁移到 4.6.1,但仍然失败。
【问题讨论】:
-
是否在 Internet Explorer 11 中加载 URL?
-
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;您的证书支持 TLS1.2? -
老实说,在这些情况下,我的建议是让证书正常工作。
-
@Fildor 我知道这只是一个例子:)
标签: c# https dotnet-httpclient