3

我可以使用以下方式获取我的浏览器网址: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

有人可以帮忙吗

4

3 回答 3

8

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

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

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

string[] segments = myUri.Segments

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

string myFolderName = segments[0];
于 2012-11-07T16:10:55.380 回答
4

您可以通过以下PathAndQuery属性获得Url

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

它会回来/MyDirectory/AnotherDir/testpage.aspx

于 2012-11-07T16:08:25.133 回答
2
 Uri uriAddr = new Uri("http://www.test.com/MyDirectory/AnotherDir/testpage.aspx");
 var firstSegment= uriAddress.Segments.Where(seg => seg != "/").First();
于 2012-11-07T16:15:40.447 回答