C# detect page redirect

The simplest way is probably to fetch the content using a HEAD request (set Method to "HEAD") in an HttpWebRequest having set AllowAutoRedirect to false. I can't remember offhand whether that will cause an exception or not, but either way it should be easy to handle.


There are a number of different codes that could be returned. You could check the various codes a la:

response.StatusCode == HttpStatusCode.Redirect

You can view all the possibilities at http://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx

Alternatively, you might find it sufficient to check whether the Location in the response is different.

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "HEAD";
request.AllowAutoRedirect = false;

string location;
using (var response = request.GetResponse() as HttpWebResponse)
{
  location = response.GetResponseHeader("Location");
}
return (location != uri.OriginalString);

Tags:

C#

.Net

Webclient