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

标签 c# .net-core httpwebrequest asp.net-core-2.0

我使用 .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;
}

关于c# - .NET Core 中 WebRequest 的重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52833655/

相关文章:

c# - 调用任何跨线程代码的最佳方式?

c# - 使用 ServiceBus SubscriptionClient 时出现 RenewLock 错误

使用 HttpWebRequest 的 C# Ebay API 订单后 check_eligibility

unix - .NET Core 中的跨平台后台服务(想想 windows 服务/unix 守护进程)?

c# - HttpWebRequest 不发送 UserAgent

c# - 通过 WebRequest 发送文件

c# - WPF 依赖属性 - 数据绑定(bind)不起作用

c# - User.IsInRole 抛出与网络相关或特定于实例的错误

c# - C# 中的空合并运算符和运算符 &&

c# - ASP.NET Core 3.1 InProcess 托管应用程序在启动异常后未重新启动