首页 > 解决方案 > 由于 SocketException 导致简单的内部 HTTP GET 请求失败:现有连接被远程主机强制关闭

问题描述

我有一个简单的健康检查系统,它向内部 URL 发送一个简单的 HTTP GET 请求,这是一个需要身份验证的 MVC Web 应用程序。例如,如果您向 发送获取请求https://{{IPAddress}}/MyMvcApp,应用程序会将您重定向到https://{{LB Host}}/MyMvcAppAuth

private static void UsingHttpGetRequest(string uri, Action<HttpWebResponse> action)
{
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

    ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback
    (
        delegate { return true; }
    );

    Log("Sending the HTTP Get request...");
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        Log($"Got a response! Status: {response.StatusCode}");
        action(response);
    }
}

我的农场有两台服务器。当此代码在其中一台服务器上运行时,它工作正常,但另一台出现此问题:

异常:System.Net.WebException:基础连接已关闭:发送时发生意外错误。---> System.IO.IOException: Unable to read data from the transport connection: 一个现有的连接被远程主机强行关闭。---> System.Net.Sockets.SocketException: 远程主机在 System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) 在 System. Net.Sockets.NetworkStream.Read(Byte[] 缓冲区,Int32 偏移量,Int32 大小)

我对此思考得越多,我就越得出这样的结论,即 F5 负载平衡器拒绝来自场中一台服务器的请求的 302 重定向。你们有什么感想?拒绝这些请求的负载均衡器上的潜在防火墙/错误配置问题?

标签: c#load-balancingtls1.2f5

解决方案


另一种方法。

       public static bool CheckPageExists(string url)
        {
            //checks only the headers to be very quick
            bool pageExists = false;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = WebRequestMethods.Http.Head;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                pageExists = response.StatusCode == HttpStatusCode.OK;
            }
            catch
            {
                return false;
            }
            return pageExists;
        }

就这样称呼它CheckPageExists("https://www.google.com")

参考using System.Net;


推荐阅读