Getting the location from a WebClient on a HTTP 302 Redirect?

It’s pretty easy to do

Let’s assume you’ve created an HttpWebRequest called myRequest

// don't allow redirects, they are allowed by default so we're going to override
myRequest.AllowAutoRedirect = false;

// send the request
HttpWebResponse response = myRequest.GetResponse();

// check the header for a Location value
if( response.Headers["Location"] == null )
{
  // null means no redirect
}
else
{
  // anything non null means we got a redirect
}

Excuse any compile errors I don’t have VS right in front of me, but I’ve used this in the past to check for redirects.

On HttpWebRequest you can set AllowAutoRedirect to false to handle the redirect yourself.

Leave a Comment