.NET Core 2.0 中的 HttpWebRequest 抛出 302 发现异常

HttpWebRequest in .NET Core 2.0 throwing 302 Found Exception

我们正在将应用程序从 .net framework 升级到 .net core 2.0。

在其中,我们使用 HttpWebRequest 联系 AllowAutoRedirect 设置为 false 的站点。当代码执行时 request.GetResponse() 该站点将 return 一个 302 响应,这在 .net 框架中是可以的 - 你可以获取响应并处理它(我们在 set-cookie header 值)。

但是,在 .net core 2.0 中,会抛出 WebException:

The remote server returned an error: (302) Found.

我的理解是否错误,因为 302 应该导致抛出异常,而不是如果 AllowAutoRedirect 设置为 false 那么响应仍然应该 returned?有什么方法可以触发在 .net 框架中遇到的相同行为吗?

我在将 AllowAutoRedirect 设置为 false 时遇到了同样的错误。 我通过在 request.GetResponse() 周围包装一个 try-catch 块并将异常的结果分配给变量

来解决这个问题
WebResponse response;
try {
   response = request.GetResponse();
}
catch(WebException e)) {
   if(e.Message.Contains("302")
      response = e.Result;
}

看看这个问题 - HttpWebRequest in .NET Core 2.0 throwing 301 Moved Permanently。简而言之,它说:

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.