Skip to main content
 首页 » 编程设计

c#中.NET Core 中 WebRequest 的重定向

2026年04月21日44jyk

我使用 .NET 4.7.1 用 C# 编写了以下程序:

var req = (HttpWebRequest) WebRequest.Create(myUrl); 
req.AllowAutoRedirect = false; 
var rsp = req.GetResponse(); 
Console.WriteLine(rsp.Headers["Location"]); 

我请求的网站正在返回 301 响应,并且“Location” header 包含要重定向到的 URL。

如果我使用 .NET Core 2.1 执行完全相同的操作,则会在调用 GetResponse 时抛出 WebException。我怎样才能避免这种情况?

请您参考如下方法:

基于this ,您需要将其捕获在 try/catch block 中并检查 WebException:

If you set AllowAutoRedirect, then you will end up not following the redirect. That means ending up with the 301 response. HttpWebRequest (unlike HttpClient) throws exceptions for non-successful (non-200) status codes. So, getting an exception (most likely a WebException) is expected. So, if you need to handle that redirect (which is HTTPS -> HTTP by the way), you need to trap it in try/catch block and inspect the WebException etc. That is standard use of HttpWebRequest.

That is why we recommend devs use HttpClient which has an easier use pattern.

类似这样的事情:

WebResponse rsp; 
 
try  
{ 
   rsp = req.GetResponse(); 
} 
 
catch(WebException ex)  
{ 
    if(ex.Message.Contains("301")) 
        rsp = ex.Result; 
}