HttpWebRequest、RestSharp等请求重定向站点无响应超时如何解决?
根本原因
- 目标站点配置了CDN/反向代理防护规则,会直接拦截没有携带标准
User-Agent请求头的请求,挂起连接直到超时 - 低版本.NET Framework(低于4.8)默认启用的TLS最高版本为TLS 1.1,当前绝大多数站点已要求使用TLS 1.2及以上版本,TLS握手失败也会导致请求无响应超时
- 部分站点跳转时会校验请求来源等header,默认自动跳转配置未携带对应参数也会被拦截
修复方案
HttpClient 修复(微软官方推荐优先使用此实现)
// 全局只初始化一次HttpClient即可,不要每次请求都新建 private static readonly HttpClient _client = new HttpClient(new HttpClientHandler() { AllowAutoRedirect = true, // 显式指定支持的TLS版本 SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13 }) { Timeout = TimeSpan.FromSeconds(30) }; static async Task Main(string[] args) { // 低版本.NET需要加这行全局配置默认TLS版本 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; // 给请求添加User-Agent头,模拟浏览器请求 using var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://www.eventim.pl"); requestMessage.Headers.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"); try { HttpResponseMessage response = await _client.SendAsync(requestMessage); response.EnsureSuccessStatusCode(); var res = response.StatusCode; Console.WriteLine((int)res); } catch (HttpRequestException e) { Console.WriteLine("Exception Caught!"); Console.WriteLine("Message :{0} ", e.Message); } }
HttpWebRequest 修复
// 全局配置TLS版本 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; HttpWebRequest init = (HttpWebRequest)WebRequest.Create(url); init.AllowAutoRedirect = true; // 添加User-Agent头 init.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"; init.Timeout = 30000; HttpWebResponse resp = (HttpWebResponse)init.GetResponse(); Console.WriteLine(resp.StatusCode);
RestSharp 修复
// 全局配置TLS版本 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13; var client = new RestClient(url); client.Timeout = 30000; client.FollowRedirects = true; var request = new RestRequest(Method.GET); // 添加User-Agent头 request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36"); IRestResponse response = client.Execute(request); Console.WriteLine(response.StatusCode);
注意事项
- 若使用.NET Core/.NET 5+版本,默认已支持TLS 1.2/1.3,可省略TLS版本配置步骤,仅添加User-Agent头即可正常请求
- 不要频繁新建HttpClient实例,会导致端口占用过多,建议全局单例复用
内容的提问来源于stack exchange,提问作者Adam Wróbel
相关产品推荐
相关产品推荐

