HttpWebRequest in .NET Core 2.0 throwing 302 Found Exception
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;
}
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
(unlikeHttpClient
) throws exceptions for non-successful (non-200) status codes. So, getting an exception (most likely aWebException
) 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 ofHttpWebRequest
.That is why we recommend devs use
HttpClient
which has an easier use pattern.