Gareth Harding Gareth Harding - 22 days ago 6
C# Question

Get where a 301 URl redirects to

I have something along the lines of:

HttpWebRequest webRequest = HttpWebRequest)WebRequest.Create("http://www.google.com/");
webRequest.AllowAutoRedirect = false;
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
HttpStatusCode wRespStatusCode = new HttpStatusCode();

try
{
response = (HttpWebResponse)webRequest.GetResponse();
wRespStatusCode = response.StatusCode;
}
catch (WebException we)
{
wRespStatusCode = ((HttpWebResponse)we.Response).StatusCode;
}

MessageBox.Show(wRespStatusCode.ToString());


which gets the status code of of an HTTP request.

In the case of a 301 "Moved Permanently" response, I was wondering how I might find the new URL that the request is being redirected to?

Answer

As indicated in the 301 status code section in the HTTP specification, look into the Location header, accessible from the HttpWebResponse.Headers property.