Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
URL拆分为C#?_C#_Asp.net - Fatal编程技术网

URL拆分为C#?

URL拆分为C#?,c#,asp.net,C#,Asp.net,我有一个类似于example.com/page?a=1&ret=/user/page2的url 我曾使用string.split(“/”)来计算路径,但在本例中,您可以看到它并不是很有用。如何拆分URL以便获得页面路径?请求。URL(Uri)对象具有许多与路径相关的有用属性。它可以为您提供整个查询字符串,以便从完整的url中删除,如果这是您想要的 您还可以在页面本身上执行Server.MapPath,然后使用FileInfo对象查看文件本身的各个部分。您可以将其加载到一个对象中并获取属性。如果您

我有一个类似于
example.com/page?a=1&ret=/user/page2
的url

我曾使用string.split(“/”)来计算路径,但在本例中,您可以看到它并不是很有用。如何拆分URL以便获得页面路径?

请求。URL(Uri)对象具有许多与路径相关的有用属性。它可以为您提供整个查询字符串,以便从完整的url中删除,如果这是您想要的


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

您可以将其加载到一个对象中并获取属性。

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

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

签出System.Uri类。它会将您的url解析为片段。

您是否考虑过使用UriBuilder。。。看


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

这似乎是使用
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");

假设您的意思是希望获得“page2”位:

那么你就必须对其余部分使用split

编辑:好的,你可以使用System.IO.Path.GetFileName WithoutExtension(第页)返回“page2”,但我不确定它对我来说是否合适


< > >代码>系统.IO.PATH .GETFLIVENAME.OFFEXIT(“示例.COM/Page=1和RET= /用户/Page 2”)< /代码>也返回“Page 2”。

< P>您也可以考虑使用ASP.NET 2内的路由API BIT,这将给您对URL路由的细粒度控制< /P> < P>这是ASP.NET项目吗?在HttpHandler/页面中,您可以简单地使用请求对象:

string path = HttpContext.Request.Path;
如果您没有HttpContext,System.Uri会提供类似的功能:

string path = new Uri("example.com/page?a=1&ret=/user/page2").AbsolutePath;
当您使用Uri()时,它具有显示url所有部分的段。如果需要返回page2部分,只需选择最后一段:

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

我会使用nvc[“ret”]而不是数字索引,但HttpUtility.ParseQueryString是一个很好的方法。UriBuilder仅在创建URI后需要修改部分URI时才有用。在本例中,Uri似乎是只读的。
string path = "http://example.com/page?a=1&ret=/user/page2";
Uri uri = new Uri(path);
Console.WriteLine(uri.Segments.LastOrDefault()); // returns page2