我有一个这样的URL:

http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye

我想从中得到http://www.example.com/mypage.aspx。

你能告诉我怎么买吗?


当前回答

System.Uri。GetComponents,只是指定你想要的组件。

Uri uri = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped);

输出:

http://www.example.com/mypage.aspx

其他回答

Silverlight的解决方案:

string path = HtmlPage.Document.DocumentUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);

你可以使用系统。Uri

Uri url = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
string path = String.Format("{0}{1}{2}{3}", url.Scheme, 
    Uri.SchemeDelimiter, url.Authority, url.AbsolutePath);

或者你可以用substring

string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
string path = url.Substring(0, url.IndexOf("?"));

编辑:修改第一个解决方案,以反映brillyfresh在评论中的建议。

这里有一个更简单的解决方案:

var uri = new Uri("http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye");
string path = uri.GetLeftPart(UriPartial.Path);

借用这里:截断查询字符串和返回干净的URL c# ASP.net

您可以使用Request.Url.AbsolutePath获取页面名,使用Request.Url.Authority获取主机名和端口。我不相信有一个内置的属性可以给你想要的东西,但你可以自己组合它们。

var canonicallink = Request.Url.Scheme + "://" + Request.Url.Authority + Request.Url.AbsolutePath.ToString();