我有一个这样的URL:

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

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

你能告诉我怎么买吗?


当前回答

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

Request.Url.GetLeftPart(UriPartial.Path)

其他回答

Request.RawUrl.Split(new[] {'?'})[0];
var canonicallink = Request.Url.Scheme + "://" + Request.Url.Authority + Request.Url.AbsolutePath.ToString();
    string url = "http://www.example.com/mypage.aspx?myvalue1=hello&myvalue2=goodbye";
    string path = url.split('?')[0];

Split()变化

我只是想添加这个变体供参考。url通常是字符串,因此使用Split()方法比Uri.GetLeftPart()更简单。当Uri抛出异常时,Split()也可以处理相对值、空值和空值。此外,url还可能包含散列,例如/report.pdf#page=10(在特定页面打开pdf)。

下面的方法处理所有这些类型的url:

   var path = (url ?? "").Split('?', '#')[0];

示例输出:

Null——>为空 空——>空 http://domain/page.html——> http://domain/page.html http://domain/page.html?q=100——> http://domain/page.html http://domain/page.html?q=100#page=2——> http://domain/page.html http://domain/page.html#page=2——> http://domain/page.html Page.html——> Page.html page.html吗?Q =100——> page.html page.html吗?Q =100#page=2——> page.html Page.html #散列——> Page.html

this.Request.RawUrl.Substring(0, this.Request.RawUrl.IndexOf('?'))