How do i check for a 302 response? WebRequest

user34537 picture user34537 · Sep 8, 2009 · Viewed 14.7k times · Source

Using WebRequest I want to know if I get a

"302 Moved Temporarily"

response instead of automatically get the new url.

Answer

devstuff picture devstuff · Sep 8, 2009

If you want to detect a redirect response, instead of following it automatically create the WebRequest and set the AllowAutoRedirect property to false:

HttpWebRequest request = WebRequest.Create(someUrl) as HttpWebRequest;
request.AllowAutoRedirect = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.Redirect || 
    response.StatusCode == HttpStatusCode.MovedPermanently)
{
    // Do something here...
    string newUrl = response.Headers["Location"];
}