网址在C#中分割?

时间:2009-06-22 23:30:59

标签: c# asp.net

我有一个像example.com/page?a=1&ret=/user/page2这样的网址。

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

10 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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"

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

编辑:嗯,您可以使用System.IO.Path.GetFileNameWithoutExtension(页面)返回“page2”,但我不确定它是否适合我。

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

答案 2 :(得分:4)

Request.Url(Uri)对象具有许多与路径相关的有用属性。它可以为你提供整个QueryString来取消完整的url,如果那是你想要的那个?

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

答案 3 :(得分:3)

您可以将其加载到URI对象中并获取Uri.AbsolutePath属性。

答案 4 :(得分:2)

这是一个ASP.NET项目吗?在您的HttpHandler / Page中,您只需使用Request对象:

string path = HttpContext.Request.Path;

如果你没有HttpContext,System.Uri会给你类似的东西:

string path = new Uri("example.com/page?a=1&ret=/user/page2").AbsolutePath;

答案 5 :(得分:0)

查看System.Uri类。它会将你的网址分解成碎片。

答案 6 :(得分:0)

您是否考虑过使用UriBuilder ...请参阅stack over question 479799

首先使用它然后拆分.Path属性

答案 7 :(得分:0)

这似乎是使用System.Uri的好例子:

Uri uri = new Uri("example.com/page?a=1&ret=/user/page2");
System.Windows.Forms.MessageBox.Show(
"Absolute URI: " + uri.AbsoluteUri + "\r\n" +
"Absolute Path: " + uri.AbsolutePath + "\r\n" +
"Local path: " + uri.LocalPath + "\r\n" +
"Host: " + uri.Host + "\r\n" +
"Port: " + uri.Port + "\r\n" +
"Query: " + uri.Query + "\r\n");

答案 8 :(得分:0)

您可能还会考虑在ASP.net 2.0中使用Routing API buit,这将为您提供对URL路由的精细控制

答案 9 :(得分:0)

当您使用 Uri() 时,它具有显示 url 的所有部分的 Segments。如果需要返回 page2 部分,只需选择最后一段:

string path = "http://example.com/page?a=1&ret=/user/page2";
Uri uri = new Uri(path);
Console.WriteLine(uri.Segments.LastOrDefault()); // returns page2