问题描述
我使用 .NET 4.7.1 在 C# 中编写了以下程序:
I wrote the following program in C# using .NET 4.7.1:
var req = (HttpWebRequest) WebRequest.Create(myUrl);
req.AllowAutoRedirect = false;
var rsp = req.GetResponse();
Console.WriteLine(rsp.Headers["Location"]);
我请求的站点返回 301 响应,并且位置"返回标头包含要重定向到的 URL.
The site I am requesting from is returning a 301 response, and the "Location" header contains the URL to redirect to.
如果我使用 .NET Core 2.1 做同样的事情,我会从对 GetResponse
的调用中得到一个 WebException
.我怎样才能避免这种情况?
If I do the exact same thing using .NET Core 2.1, I will instead get a WebException
thrown from the call to GetResponse
. How can I avoid this?
推荐答案
基于 this,您需要将其捕获在 try/catch
块中并检查 WebException
:
Based on this, you need to trap it in try/catch
block and inspect the WebException
:
如果您设置了 AllowAutoRedirect
,那么您最终将不遵循重定向.这意味着以 301 响应结束.HttpWebRequest
(与 HttpClient
不同)为不成功(非 200)抛出异常状态码.因此,获得异常(很可能是 WebException
)是预期的.So,如果您需要处理该重定向(即 HTTPS ->顺便说一下 HTTP),您需要将其捕获在 try/catch 块中并检查WebException 等. 那是 HttpWebRequest
的标准用法.
这就是我们推荐开发者使用 HttpClient
的原因,它更容易使用模式.
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;
}
这篇关于.NET Core 中 WebRequest 的重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!