2009-09-08 32 views

Trả lời

32

Nếu bạn muốn phát hiện một phản ứng chuyển hướng, thay vì sau đó tự động tạo ra các WebRequest và thiết lập AllowAutoRedirect tài sản để 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"]; 
} 
+1

Chưa tự xác minh điều này, nhưng tôi chỉ tìm thấy nội dung: "Nếu thuộc tính HttpWebRequest.AllowAutoRedirect là false, HttpStatusCode.Found sẽ gây ra một ngoại lệ để được ném. " Nguồn: http://www1.cs.columbia.edu/~lok/csharp/refdocs/System.Net/types/HttpStatusCode.htm –

+0

@Nathan: Tôi không thực sự thấy như thế nào, vì HttpStatusCode là một enum. Tài liệu được liên kết (cần kết thúc bằng '.html' BTW) dường như đã lỗi thời; câu đó có lẽ là một lỗi cắt và dán. – devstuff

+0

BTW, bạn cũng có thể sử dụng HttpStatusCode.Redirect (một bí danh khác cho 302), điều này rõ ràng hơn một chút. – devstuff

3

Giống như vậy:

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

Mã nên được

HttpStatusCode.TemporaryRedirect 
+1

HttpStatusCode.TemporaryRedirect là 307. http://www1.cs.columbia.edu/~lok/csharp/refdocs/System.Net/types/HttpStatusCode.html#TemporaryRedirect –

+0

Bây giờ tôi có thể thấy mã phản hồi, nhưng nó vẫn chuyển hướng và cho tôi 'OK' –

+0

@Nathan Taylor: Tôi sao chép/dán những gì CURL đã cho tôi sử dụng curl -I "url" –

1

VB Net Cod e

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 
Các vấn đề liên quan