NET Core中的WebRequest重定向 [英] Redirect of WebRequest in .NET Core
问题描述
我使用.NET 4.7.1用C#编写了以下程序:
I wrote the following program in C# using .NET 4.7.1:
var req = (HttpWebRequest) WebRequest.Create(myUrl);
req.MediaType = "GET";
req.AllowAutoRedirect = false;
var rsp = req.GetResponse();
Console.WriteLine(rsp.Headers["Location"]);
我所请求的网站返回了301响应,"Location"(位置)标头包含要重定向到的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?
推荐答案
基于此,您需要将其捕获在 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
)是预期的.S o,如果您需要处理该重定向(即HTTPS->HTTP),您需要将其捕获在try/catch块中并进行检查WebException等..这是HttpWebRequest
的标准用法.
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
.
这就是我们建议开发人员使用 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重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!