.NET Core 2.0中的HttpWebRequest引发302发现异常 [英] HttpWebRequest in .NET Core 2.0 throwing 302 Found Exception
问题描述
我们正在将应用程序从.net框架升级到.net core 2.0.
We are upgrading our application from .net framework to .net core 2.0.
在其中,我们使用HttpWebRequest
与AllowAutoRedirect
设置为false的站点联系.当执行代码request.GetResponse()
时,该站点将返回302响应,在.net框架中该响应正常-您可以获取响应并进行处理(我们在set-cookie
标头值之后).
In it, we use a HttpWebRequest
to contact a site with AllowAutoRedirect
set to false. When the code executed request.GetResponse()
The site will return a 302 response, which in .net framework is OK - you can take response and handle it (we are after the set-cookie
header value).
但是,在.net core 2.0中,抛出了WebException:
However, in .net core 2.0, a WebException gets thrown:
The remote server returned an error: (302) Found.
我的理解是错误的,因为302应该导致引发异常,而不是如果AllowAutoRedirect设置为false,那么仍然应该返回响应?有什么方法可以触发.net框架中遇到的相同行为?
Is my understanding incorrect in that a 302 should result in an exception being thrown, rather if AllowAutoRedirect is set to false then the response should still be returned? Is there any way to trigger the same behavior experienced in .net framework?
推荐答案
将AllowAutoRedirect
设置为false
时遇到相同的错误.
我通过在request.GetResponse()
周围包裹一个try-catch
块并将异常结果分配给变量来解决了这个问题
I got the same error when setting AllowAutoRedirect
to false
.
I solved the problem by just wrapping a try-catch
-block around request.GetResponse()
and assigning the Result of the exception to a variable
WebResponse response;
try {
response = request.GetResponse();
}
catch(WebException e)) {
if(e.Message.Contains("302")
response = e.Result;
}
这篇关于.NET Core 2.0中的HttpWebRequest引发302发现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!