Search code examples
c#httpwebrequesthttp-status-codeshttpwebresponsehttp-redirect

How can I detect if a URL is redirected to another one?


I use this code to make a 'GET' request to urls.

var request = WebRequest.Create(uri) as HttpWebRequest;
request.Method = "GET";
var response = request.GetResponse() as HttpWebResponse;
var status = response.StatusCode; // returns HttpStatusCode.OK

So, the probelem is when a url is redirected to another one, I can't detect it. For example;

url is: http://site.com

that redirects to http://www.site.com

but when I make a request to http://site.com it returns a HttpStatusCode.OK for it -instead of a redirect code. Have you any idea please?


Solution

  • You can use the AllowAutoRedirect property. Set it to false and handle the redirect yourself.