我有一个这样的URL:

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

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

你能告诉我怎么买吗?


当前回答

我已经创建了一个简单的扩展,因为其他一些答案抛出空异常,如果没有QueryString开始:

public static string TrimQueryString(this string source)
{ 
    if (string.IsNullOrEmpty(source))
            return source;

    var hasQueryString = source.IndexOf('?') != -1;

    if (!hasQueryString)
        return source;

    var result = source.Substring(0, source.IndexOf('?'));

    return result;
}

用法:

var url = Request.Url?.AbsoluteUri.TrimQueryString() 

其他回答

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

我已经创建了一个简单的扩展,因为其他一些答案抛出空异常,如果没有QueryString开始:

public static string TrimQueryString(this string source)
{ 
    if (string.IsNullOrEmpty(source))
            return source;

    var hasQueryString = source.IndexOf('?') != -1;

    if (!hasQueryString)
        return source;

    var result = source.Substring(0, source.IndexOf('?'));

    return result;
}

用法:

var url = Request.Url?.AbsoluteUri.TrimQueryString() 

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

Silverlight的解决方案:

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

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

Request.Url.GetLeftPart(UriPartial.Path)