Question

When making a request to a server, in the code a 401 Unauthorized exception is thrown. However, in a network trace I can see the server is actually returning a 302 status.

My code is pretty simple, I have a Authorization Basic header and create the connection like this.

try
{
    using (HttpWebResponse remoteResp = (HttpWebResponse)httpReq.GetResponse())
    {
       //do stuff
    }
}
catch (Exception e)
{
    //401 here instead of 302
}

What am I missing to get the 302 in my code?

Was it helpful?

Solution

By default HttpWebRequest follows redirects before returning a result. You can turn off this behavior as follows:

httpReq.AllowAutoRedirect = false;

If you want to allow a specific number of redirections, but no more, then you can set the MaximumAutomaticRedirections property, which is 50 by default.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top