views:

455

answers:

2

Using WebRequest i want to know if i get a "302 Moved Temporarily" response instead of automatically get the new url

+3  A: 

Like so:

HttpWebResponse response;
int code = (int) response.StatusCode;

The code should be

HttpStatusCode.TemporaryRedirect
Noon Silk
HttpStatusCode.TemporaryRedirect is a 307. http://www1.cs.columbia.edu/~lok/csharp/refdocs/System.Net/types/HttpStatusCode.html#TemporaryRedirect
Nathan Taylor
I can now see the reponse code, but it still redirects and gives me 'OK'
acidzombie24
@Nathan Taylor: I copy/pasted what CURL gave me using curl -I "url"
acidzombie24
+4  A: 

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

HttpWebRequest req = WebRequest.Create(someUrl) as HttpWebRequest;
req.AllowAutoRedirect = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.Found) // Found == 302
{
    // Do something...
    string newUrl = response.Headers["Location"];
}
devstuff
Haven't verified this myself, but I just found something saying: "If the HttpWebRequest.AllowAutoRedirect property is false, HttpStatusCode.Found will cause an exception to be thrown." Source: http://www1.cs.columbia.edu/~lok/csharp/refdocs/System.Net/types/HttpStatusCode.htm
Nathan Taylor
@Nathan: I don't really see how, since HttpStatusCode is an enum. The linked documentation (needs to end in '.html' BTW) appears to be out of date; that sentence was probably a cut-and-paste bug.
devstuff
BTW, you can also use HttpStatusCode.Redirect (another alias for 302), which is a bit more obvious.
devstuff