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
2009-09-08 00:10:51
HttpStatusCode.TemporaryRedirect is a 307. http://www1.cs.columbia.edu/~lok/csharp/refdocs/System.Net/types/HttpStatusCode.html#TemporaryRedirect
Nathan Taylor
2009-09-08 00:34:16
I can now see the reponse code, but it still redirects and gives me 'OK'
acidzombie24
2009-09-08 00:47:06
@Nathan Taylor: I copy/pasted what CURL gave me using curl -I "url"
acidzombie24
2009-09-08 00:47:44
+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
2009-09-08 00:26:44
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
2009-09-08 00:41:23
@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
2009-09-08 03:12:07
BTW, you can also use HttpStatusCode.Redirect (another alias for 302), which is a bit more obvious.
devstuff
2009-09-08 03:14:01