HttpWebRequest in .NET Core 2.0 throwing 302 Found Exception
Asked Answered
D

2

16

We are upgrading our application from .net framework to .net core 2.0.

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).

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

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

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?

Dedradedric answered 10/8, 2017 at 3:34 Comment(1)
For others who arrive here too, I'm experience some differences in the cookie behaviour from .NET Framework to .NET Core, the "HttpOnly" flag appears to be set differently too.Erickson
T
16

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;
}
Transcript answered 16/9, 2017 at 19:51 Comment(2)
It is supposed to be e..ResponseKnut
I'd suggest a slight modification to the catch block; catch (WebException ex) { response = (HttpWebResponse)ex.Response; if(response.StatusCode != HttpStatusCode.Redirect) throw (ex); } makes things a little more concise rather than relying on a consistent string message.Erickson
U
2

Take a look at this issue - HttpWebRequest in .NET Core 2.0 throwing 301 Moved Permanently. In short, it says:

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.

Ultimate answered 7/8, 2018 at 8:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.