【问题标题】:How to grab .aspx Page Name from the URL?如何从 URL 中获取 .aspx 页面名称?
【发布时间】:2009-12-02 14:40:17
【问题描述】:

我可以使用什么对象从 URL 中获取当前的 PageName.aspx(包括扩展名 .aspx)?当我在页面上时,我找不到允许我抓取它的对象和方法。

【问题讨论】:

  • 你可以用谷歌搜索你知道的。在 google 内的 asp.net 中输入 get page name ,效果非常好。
  • 如果“谷歌搜索”购买了堆栈溢出页面,那么您应该发布该问题/答案。如果没有,那么应该像这样在这里询问,以便 StackOverflow 是任何“谷歌搜索”的第一个呼叫端口。
  • @LymanZerga 和 @Robin Day,谷歌上的第一个答案(也许还有其他答案),在我的搜索中是 www.aspcode.net/Get-current-page-name.aspx,导致基于FileInfo 的解决方案。请参阅下面关于它的缺点的答案。这就是为什么这个看似微不足道的问题仍然值得好好讨论,分享我们所有人的知识和经验。干杯!

标签: asp.net


【解决方案1】:

请注意,有时,在 GoDaddy 等共享主机上,您可能无权创建新的 FileInfo 对象。是的,相信它。

所以我建议你使用这个sn-p:

string fullPath = /* System.Web.HttpContext.Current. (optional in most cases) */ Request.Url.AbsolutePath;
string fileName = System.IO.Path.GetFileName(fullPath);

享受:-)

【讨论】:

  • 确实非常好,尤其是包含在一个声明中:System.IO.Path.GetFileNameWithoutExtension(Request.Url.AbsolutePath)
  • 大概GetFileNameGetFileNameWithoutExtension 只是解析传入的名称,实际上并没有对文件系统做任何事情......
【解决方案2】:

Pino 的来源是 lil man:http://www.devx.com/tips/Tip/42433

  string sPagePath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
    System.IO.FileInfo oFileInfo = new System.IO.FileInfo(sPagePath);
    string sPageName = oFileInfo.Name;

【讨论】:

    【解决方案3】:

    http://www.aspcode.net/Get-current-page-name.aspx

    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; 
    } 
    

    【讨论】:

      【解决方案4】:
      Request.Url.AbsolutePath
      

      关于'/'的拆分,最后一项是你的文件名。

      【讨论】:

        【解决方案5】:

        Path.GetFileName(Request.PhysicalPath) 可用于获取实际文件名

        【讨论】:

          【解决方案6】:

          我使用:Request.Url.LocalPath,它给了我“/default.aspx”,即使完整的 URL 是 https://www.example.com/?foo=bar。你只需要去掉前面的/

          【讨论】:

            【解决方案7】:

            这个怎么样:

                var pageName = System.IO.Path.GetFileName(Request.Url.ToString());
                Response.Write(pageName);
            

            【讨论】:

              【解决方案8】:
              string pageName = Path.GetFileName(Request.Path);
              

              【讨论】:

                猜你喜欢
                • 2014-03-14
                • 1970-01-01
                • 2019-03-06
                • 2011-07-17
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多