2013-05-15 58 views
2

我知道這很容易,但我忘記了如何以及因爲我不記得它叫什麼了;試圖尋找解決方案一直很困難。獲取被請求/被請求的頁面的名稱

我們如何在C#中請求頁面名稱?

如:

String pageName = String.Empty; 
if(IsPost) 
{ 
    pageName = Request.PageName; // example only 
} 

回答

1

爲了使答案更清潔

public string GetPageName() 
{ 
    string path = System.Web.HttpContext.Current.Request.Url.AbsolutePath; 
    System.IO.FileInfo info = new System.IO.FileInfo(path); 
    return info.Name; 
} 
+1

謝謝@Ashley!上面的代碼給出了完整的文件路徑,我擴展了它一點,所以它只給出了文件名沒有擴展名:'string pageName = Path.GetFileNameWithoutExtension(HttpContext.Current.Request.Url.AbsoluteUri);' –

1

如果你只是想在.aspx文件名:

pageName = Page.Request.Url.Segments[Page.Request.Url.Segments.Length - 1]; 

有使用的一些好的樣品URI類: http://www.dotnetperls.com/uri

0
string pageName = Request.UrlReferrer != null ? System.IO.Path.GetFileName(Request.UrlReferrer.AbsolutePath) : Request.Url.Segments[Request.Url.Segments.Length - 1]; 

這也可以用於Url重寫。

+0

我相信這將工作所有時間沒有URLReferer的東西: pageName = new System.Text.RegularExpressions.Regex(「_(。*?)_ aspx」)。Match(this.Page.ToString())。Groups [1] .Value; – mmtakn