c# - 由于 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 大小)
- 我比较了服务器之间的 IIS 配置设置,发现没有显着差异。
- 我比较了注册表项,发现两台服务器都没有注册表项“SchUseStrongCrypto”,但两台服务器上肯定都启用了 TLS 1.2。
- 已验证两者都安装了 .NET v4.0.30319。
我对此思考得越多,我就越得出这样的结论,即 F5 负载平衡器拒绝来自场中一台服务器的请求的 302 重定向。你们有什么感想?拒绝这些请求的负载均衡器上的潜在防火墙/错误配置问题?
解决方案
另一种方法。
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;
推荐阅读
- visual-studio-code - 在远程 VS 代码工作区中未检测到 Git 存储库
- python - Tensorflow 无法拆分 Unicode UTF-8 字符
- reactjs - Material UI - 使用 React Hook 表单自动完成
- angular - Angular // 带有图表(图表 js)的组件在我刷新页面之前不会显示
- bash - Mac 无法读取 DOS 文件,必须使用 dos2unix
- android - 这是使用 AsyncTask 的问题吗?需要整理我的代码
- node.js - 来自 Vue/Nuxt 应用程序的 axios 请求超时,服务器没有响应,但相同的 Curl 请求得到响应
- azure - 无效资源 AADSTS500011
- python - minus between 2 dataframe based on column
- javascript - 将数据从 Angular 防护传递到组件失败