2011-01-28 319 views
33

我想寫一個c#方法來檢索當前頁面。 eg Default6.aspx我知道我可以做到以下幾點:從url獲取當前頁面

string url = HttpContext.Current.Request.Url.AbsoluteUri; 
// http://localhost:1302/TESTERS/Default6.aspx 

string path = HttpContext.Current.Request.Url.AbsolutePath; 
// /TESTERS/Default6.aspx 

string host = HttpContext.Current.Request.Url.Host; 
// localhost 

但我怎樣才能得到Default6.aspx?而且如果該網址是http://localhost:1302/TESTERS/,我的方法應該返回Default.aspx的

回答

40
Path.GetFileName(Request.Url.AbsolutePath) 
+6

認爲應該是'Path.GetFileName(Request.Url.AbsolutePath)' – user489998 2011-10-28 10:42:44

5

像下面一個簡單的功能將幫助:

public string GetCurrentPageName() 
{ 
    string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath; 
    System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath); 
    string sRet = oInfo.Name; 
    return sRet; 
} 
6

試試這個:

path.Substring(path.LastIndexOf("/"); 
+0

順便說一句,這將返回「/ MyPage.aspx」。另外,對於VB.Net用戶,你可以嘗試`Request.Path.Substring(Request.Path.LastIndexOf(「/」))` – cjbarth 2014-03-11 19:36:20

+0

不是一個好方法。你會得到相同的東西,作爲@ cl0rkster – Mike 2017-07-13 17:27:58

12

你需要的類是System.Uri

Dim url As System.Uri = Request.UrlReferrer 
Debug.WriteLine(url.AbsoluteUri) ' => http://www.mysite.com/default.aspx 
Debug.WriteLine(url.AbsolutePath) ' => /default.aspx 
Debug.WriteLine(url.Host)   ' => http:/www.mysite.com 
Debug.WriteLine(url.Port)   ' => 80 
Debug.WriteLine(url.IsLoopback) ' => False 

http://www.devx.com/vb2themax/Tip/18709

1

您可以在下面試試。

string url = "http://localhost:1302/TESTERS/Default6.aspx"; 

string fileName = System.IO.Path.GetFileName(url); 

希望這會有所幫助。

1
Request.Url.Segments.Last() 

另一種選擇。