2011-11-18 143 views
6

可能重複:
How to get the URL of the current page in C#如何獲取當前URL

如果我在一個頁面說http://myweb/folder/obtain.aspx?thevalue=3,我怎麼能確定如果URL包含在C#obtain.aspx?thevalue?我只需要檢查用戶是否登陸這個特定的頁面。

PS:我想我並不真正需要檢查的?thevalue,但只是obtain.aspx

+0

@RichardD有這些問題的答案沒有解釋如何得到實際的網頁/文件降落的名字,他們只是說明如何獲取URL。根據標題他們是相同的,但問題內容使他們不同。 – Nate

回答

9

試試這個:

//gets the current url 
string currentUrl = Request.Url.AbsoluteUri; 

//check the url to see if it contains your value 
if (currentUrl.ToLower().Contains("obtain.aspx?thevalue")) 
    //do something 
+1

+1,因爲有時鏈接是UPPER或標題或小寫。 – Rippo

+0

如果我在URL中有'#',那麼該怎麼辦...... ie http://myweb/folder/obtain.aspx#commentfocus –

0

Request.Url將返回用戶所請求的確切URI。

如果要專門爲thevalue檢查,你可能會更好過在Request.QueryString

1

Request.Url尋找那應該包含你所需要的一切。在你的情況,你可以使用類似

if(Request.Url.PathAndQuery.IndexOf("obtain.aspx") >= 0)... 
1

我建議使用Request.Url。爲了得到確切的文件名,您可以嘗試使用也System.IO.Path

var aspxFile = System.IO.Path.GetFileName(Request.Url.LocalPath); 
var landed = aspxFile.Equals("obtain.aspx", StringComparison.InvariantCultureIgnoreCase); 
if(landed) { // your code } 
1

這會給你確切的文件名(obtain.aspx) Request.Url.Segments [1]

0

它的醜陋,但你CAND嘗試

if (HttpContext.Current.HttpRequest.Url.AbsolutePath.Contains("/obtain.aspx")) 
// then do something 
+0

包含將爲「2obtain.aspx」賦予正確的值...... Equals()should被使用&System.IO.Path.GetFileName(Request.Url.LocalPath); – Kim

+0

事實上,會更好 –