【问题标题】:Get anything after first slash in URL在 URL 中的第一个斜杠后获取任何内容
【发布时间】:2012-10-27 17:32:15
【问题描述】:

我可以使用:string url = HttpContext.Current.Request.Url.AbsoluteUri; 获取我的浏览器网址 但是说如果我有一个如下的网址:

http://www.test.com/MyDirectory/AnotherDir/testpage.aspx

我如何获得其中的“MyDirectory”部分,.NET 中是否有实用程序来获得它,或者我是否需要字符串操作?

如果我在“/”的第一个实例之后进行字符串操作并说什么,那么它不会在 http: 之后返回斜杠吗?如果我的网址是www.test.com/MyDirectory/AnotherDir/testpage.aspx

,它会起作用

有人可以帮忙

【问题讨论】:

  • 您是否检查了该类的其他属性,例如AbsolutePath?

标签: c# url slash


【解决方案1】:

你可以通过UrlPathAndQuery属性得到这个

var path = HttpContext.Current.Request.Url.PathAndQuery;

它将返回/MyDirectory/AnotherDir/testpage.aspx

【讨论】:

    【解决方案2】:

    从你的 url 实例化一个 Uri 实例:

    Uri myUri = new Uri("http://www.test.com/MyDirectory/AnotherDir/testpage.aspx");
    

    然后您可以使用以下方法将路径段放入字符串数组中:

    string[] segments = myUri.Segments
    

    您的第一个“MyDirectory”文件夹将位于:

    string myFolderName = segments[0];
    

    【讨论】:

    • 谢谢你,这正是我所需要的。
    【解决方案3】:
     Uri uriAddr = new Uri("http://www.test.com/MyDirectory/AnotherDir/testpage.aspx");
     var firstSegment= uriAddress.Segments.Where(seg => seg != "/").First();
    

    【讨论】:

      猜你喜欢
      • 2011-11-07
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 2011-08-09
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 2014-10-22
      相关资源
      最近更新 更多