2012-04-14 35 views
2

我有一個URL將我重定向到另一個網站。我想從C#中的原始URL中獲取目標網址。有沒有辦法遵循這些重定向?如何獲取網站重定向目標網址(最終用戶鏈接)

+0

你有一個網址,和你在做什麼用它?使用WebRequest? – 2012-04-14 16:23:42

+0

我只需要「最終用戶鏈接」。我試圖加載webbrowser控件,但是當我得到當前頁面的位置時,它只顯示第一個url,而不是目標。 – Pmillan 2012-04-14 16:26:40

回答

4

您可以使用HttpWebRequest類

var request = (HttpWebRequest)WebRequest.Create(someUrl); 
request.AllowAutoRedirect = false; 
var response = (HttpWebResponse) request.GetResponse(); 
if (response.StatusCode == HttpStatusCode.Found) // Found == 302 
{ 
    // Do something... 
    string newUrl = response.Headers["Location"]; 
} 

此外,您還可以通過設置自動跟隨重定向:

request.AllowAutoRedirect = true; 
request.MaximumAutomaticRedirections = 4; //number of redirections allowed 

相關:How do i check for a 302 response? WebRequest

+1

response.ResponseUri.OriginalString讓我得到我所需要的。 – Pmillan 2012-04-14 16:40:48

+1

Minor nit:我更喜歡強制轉換爲'(HttpWebRequest)'和'(HttpWebResponse)',因爲如果對象不是正確的類型,那麼'as'將返回null,並且您將在該對象上得到一個'NullReferenceException' _下一行。最好在包含問題的行上立即得到'InvalidCastException'。 – 2012-04-14 16:55:41

+0

@約翰桑德斯同意!我更改了代碼 – jorgebg 2012-04-14 17:30:21