网址在C#中分割?

8 c# asp.net

我有一个网址example.com/page?a=1&ret=/user/page2.

我使用string.split('/')来计算路径但是在这种情况下你可以看到它不是很有用.如何拆分URL以便获取页面路径?

dah*_*byk 25

如果从字符串中创建System.Uri对象,它将具有路径的不同部分的多个属性:

string path = "http://example.com/page?a=1&ret=/user/page2";
Uri uri = new Uri(path);
Console.WriteLine(uri.AbsolutePath); // Prints "/page"
Run Code Online (Sandbox Code Playgroud)


Rob*_*Day 5

Request.Url (Uri) 对象具有许多与路径相关的有用属性。如果这就是您所追求的,它可以为您提供整个 QueryString 以摆脱完整的 url?

您还可以在页面本身上执行 Server.MapPath,然后使用 FileInfo 对象查看文件本身的各个部分。


Ric*_*ein 5

假设你的意思是想要获得"page2"位:

 var ub = new UriBuilder("example.com/page?a=1&ret=/user/page2");
 NameValueCollection nvc = HttpUtility.ParseQueryString(ub.Query);
 string page = nvc[nvc.Count - 1]; // gets "/user/page2"
Run Code Online (Sandbox Code Playgroud)

然后你将不得不使用拆分.

编辑:嗯,您可以使用System.IO.Path.GetFileNameWithoutExtension(页面)返回"page2",但我不确定它对我来说是对的.

System.IO.Path.GetFileNameWithoutExtension("example.com/page?a=1&ret=/user/page2") 也返回"page2".