Search code examples
c#.net-corehttpwebrequestasp.net-core-2.0

Redirect of WebRequest in .NET Core


I wrote the following program in C# using .NET 4.7.1:

var req = (HttpWebRequest) WebRequest.Create(myUrl);
req.AllowAutoRedirect = false;
var rsp = req.GetResponse();
Console.WriteLine(rsp.Headers["Location"]);

The site I am requesting from is returning a 301 response, and the "Location" header contains the URL to redirect to.

If I do the exact same thing using .NET Core 2.1, I will instead get a WebException thrown from the call to GetResponse. How can I avoid this?


Solution

  • Based on this, you need to trap it in try/catch block and inspect the WebException:

    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.

    Something like this:

    WebResponse rsp;
    
    try 
    {
       rsp = req.GetResponse();
    }
    
    catch(WebException ex) 
    {
        if(ex.Message.Contains("301"))
            rsp = ex.Result;
    }