我有一个这样的URL:

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

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

你能告诉我怎么买吗?


当前回答

你可以使用系统。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在评论中的建议。

其他回答

好的答案也在这里找到了答案来源

Request.Url.GetLeftPart(UriPartial.Path)

这是我的解决方案:

Request.Url.AbsoluteUri.Replace(Request.Url.Query, String.Empty);
var canonicallink = Request.Url.Scheme + "://" + Request.Url.Authority + Request.Url.AbsolutePath.ToString();
Request.RawUrl.Split(new[] {'?'})[0];

我的方法:

new UriBuilder(url) { Query = string.Empty }.ToString()

or

new UriBuilder(url) { Query = string.Empty }.Uri