【问题标题】:get current page from url从 url 获取当前页面
【发布时间】:2011-06-17 09:01:39
【问题描述】:

我想编写一个 c# 方法来检索当前页面。例如 Default6.aspx 我知道我可以执行以下操作:

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?如果url是http://localhost:1302/TESTERS/,我的方法应该返回default.aspx

【问题讨论】:

    标签: c# url request


    【解决方案1】:

    如下所示的简单函数会有所帮助:

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

    【讨论】:

      【解决方案2】:

      试试这个:

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

      【讨论】:

      • 顺便说一句,这将返回“/MyPage.aspx”。此外,对于 VB.Net 用户,您可以尝试Request.Path.Substring(Request.Path.LastIndexOf("/"))
      【解决方案3】:

      你需要的课程是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

      【讨论】:

        【解决方案4】:

        你可以在下面试试这个。

        string url = "http://localhost:1302/TESTERS/Default6.aspx";
        
        string fileName = System.IO.Path.GetFileName(url);
        

        希望这会有所帮助。

        【讨论】:

          【解决方案5】:
          Path.GetFileName( Request.Url.AbsolutePath )
          

          【讨论】:

          • 认为应该是'Path.GetFileName(Request.Url.AbsolutePath)'
          • 如果我在 URL 中有 '#' 怎么办..... 即:http:test.abc.com/sitesposure.aspx#commentfocus ......... 会起作用吗?
          【解决方案6】:
          Request.Url.Segments.Last()
          

          另一种选择。

          【讨论】:

          • 这不是一个好方法。例如:www.mysite.com/Product/3。页面的名称可能是产品,甚至可能是详细信息或索引。您的语句将返回 3。不是页面名称,甚至不是来自 url 的正确参数。
          • 如果您使用任何 URL 重写,我绝对同意它没有用。但是,如果您正在使用 URL 重写(例如您的示例),那么问题中 Default6.aspx 的等效项是什么?
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-28
          • 2014-05-26
          • 2021-07-23
          • 2016-09-28
          • 2013-03-01
          • 1970-01-01
          相关资源
          最近更新 更多