HttpWebRequest in .NET Core 2.0 throwing 302 Found exception

We upgrade our application from .net structure to .net core 2.0.

In it, we use HttpWebRequestto contact the site with AllowAutoRedirectset to false. When the code is executed, the request.GetResponse()Site will return the answer 302, which is fine in the .NET Framework - you can take the answer and process it (we are after the header sign set-cookie).

However, in .net core 2.0, a WebException is thrown:

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

I understand that the misconception that 302 should throw an exception, and if the AllowAutoRedirect parameter is set to false, should the response be returned? Is there a way to cause the same behavior as in the .net framework?

+9
source share
2 answers

I got the same error when installing AllowAutoRedirecton false. I solved the problem by simply wrapping try-catch-block around request.GetResponse()and assigning an exception result to a variable

WebResponse response;
try {
   response = request.GetResponse();
}
catch(WebException e)) {
   if(e.Message.Contains("302")
      response = e.Result;
}
+8
source

Take a look at this issue - HttpWebRequest in .NET Core 2.0 throwing 301 has been moved forever . In short, it says:

If you install AllowAutoRedirect, then you will ultimately not follow the redirect. That means ending up with a response of 301.

HttpWebRequest ( HttpClient) HttpClient HttpClient ( 200) . , ( , WebException).

, (, HTTPS → HTTP), try/catch, WebException .. HttpWebRequest.

HttpClient .

+1

Source: https://habr.com/ru/post/1683389/


All Articles