我使用 .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
(unlikeHttpClient
) throws exceptions for non-successful (non-200) status codes. So, getting an exception (most likely aWebException
) 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 ofHttpWebRequest
.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;
}
关于c# - .NET Core 中 WebRequest 的重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52833655/