17

Using WebRequest I want to know if I get a

"302 Moved Temporarily"

response instead of automatically get the new url.

Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68

3 Answers3

34

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

HttpWebRequest request = WebRequest.Create(someUrl) as HttpWebRequest;
request.AllowAutoRedirect = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
if (response.StatusCode == HttpStatusCode.Redirect || 
    response.StatusCode == HttpStatusCode.MovedPermanently)
{
    // Do something here...
    string newUrl = response.Headers["Location"];
}
Bryan
  • 2,870
  • 24
  • 39
  • 44
devstuff
  • 8,277
  • 1
  • 27
  • 33
  • 1
    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 Sep 08 '09 at 00:41
  • @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 Sep 08 '09 at 03:12
  • BTW, you can also use HttpStatusCode.Redirect (another alias for 302), which is a bit more obvious. – devstuff Sep 08 '09 at 03:14
  • amended the alias and added 301 as well – Sam Saffron Apr 26 '12 at 05:50
  • 1
    Another tweak; can use `response.Headers[HttpResponseHeader.Location]` in your "do something" example as well (analogous to the status code constants). – Matt Enright Jun 20 '12 at 19:26
3

Like so:

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

The code should be

HttpStatusCode.TemporaryRedirect
Noon Silk
  • 54,084
  • 6
  • 88
  • 105
  • 1
    HttpStatusCode.TemporaryRedirect is a 307. http://www1.cs.columbia.edu/~lok/csharp/refdocs/System.Net/types/HttpStatusCode.html#TemporaryRedirect – Nathan Taylor Sep 08 '09 at 00:34
  • I can now see the reponse code, but it still redirects and gives me 'OK' –  Sep 08 '09 at 00:47
  • @Nathan Taylor: I copy/pasted what CURL gave me using curl -I "url" –  Sep 08 '09 at 00:47
1

VB Net Code

Function GetRealUrl(someUrl As String) As String
        Dim req As HttpWebRequest = TryCast(WebRequest.Create(someUrl), HttpWebRequest)
        req.AllowAutoRedirect = False
        Dim response As HttpWebResponse = TryCast(req.GetResponse(), HttpWebResponse)
        If response.StatusCode = HttpStatusCode.Redirect OrElse response.StatusCode = HttpStatusCode.MovedPermanently Then
            ' Do something...
            Dim newUrl As String = response.Headers("Location")
            getrealurl = newUrl
        Else
            getrealurl = someUrl
        End If
End Function
Bridge
  • 29,818
  • 9
  • 60
  • 82
Zibri
  • 9,096
  • 3
  • 52
  • 44