.NET Core 中 WebRequest 的重定向 [英] Redirect of WebRequest in .NET Core

查看:25
本文介绍了.NET Core 中 WebRequest 的重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 .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 的标准用法.

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.

这就是我们推荐开发者使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆