使用 HttpClient 连接到 Azure Frontdoor 时获取“现有连接被远程主机强制关闭”

问题描述 投票:0回答:1

我们有一些 .NET 代码调用位于 Azure Frontdoor 后面的 Azure 网站。该代码使用 HttpClient 以非常简单的方式进行调用。通过 Azure Frontdoor 调用我们的站点时,我们开始收到以下错误。

现有连接被远程主机强制关闭

  • .NET Framework 4.6、.NET Framework 4.7 和 .NET Core 3.1 会发生这种情况。
  • 实际的 Frontdoor 站点名称并不重要。任何以
    xxxx.azurefd.net
    结尾的内容都会生成此错误。
  • 相同的代码可以直接访问应用程序,没有问题。
  • 我可以在不同的 Windows 计算机上复制此错误。我的笔记本电脑运行的是 Windows 10。我们还在 Windows Server 2012 和其他运行 Windows 10 的计算机上看到了这种行为。这些企业计算机有时在代理后面运行,但即使不在防火墙/代理后面,它们仍然会生成错误。
  • 我们怀疑这是某种类型的 TLS 相关错误,因为如果您不使用自定义域,Azure Frontdoor 仅支持 TLS1.2,但显式添加 TLS12 似乎根本没有帮助。

以下代码会产生问题。

static async Task Main(string[] args)
{
    if (ServicePointManager.SecurityProtocol.HasFlag(SecurityProtocolType.Tls12) == false)
    {
        ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls12;
    }

    ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
    Console.WriteLine($"Protocol: {ServicePointManager.SecurityProtocol}");

    var client = new HttpClient { BaseAddress = new Uri("https://anything.azurefd.net") };

    try
    { 
        var result = await client.GetAsync("someroute");
        Console.WriteLine(await result.Content.ReadAsStringAsync());
    }
    catch(Exception e)
    {
        while(e != null)
        {
            Console.WriteLine(e.Message);
            e = e.InnerException;
        }
    }

    Console.ReadLine();
}

提前致谢。

c# azure tls1.2 azure-front-door
1个回答
0
投票

最有可能的是,使用 HttpClient 访问 Azure Frontdoor 时的连接问题与 TLS 配置或兼容性有关。在初始化 HttpClient 之前,您应该尝试将 ServicePointManager.SecurityProtocol 专门设置为 SecurityProtocolType.Tls12。

我想尝试一下:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new HttpClient { BaseAddress = new Uri("https://anything.azurefd.net") };
© www.soinside.com 2019 - 2024. All rights reserved.