Get url without querystring

前端 未结 18 2071
后悔当初
后悔当初 2020-11-28 21:24

I have a URL like this:

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

I want to get http://www.example.com/mypage

18条回答
  •  春和景丽
    2020-11-28 21:51

    I've created a simple extension, as a few of the other answers threw null exceptions if there wasn't a QueryString to start with:

    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;
    }
    

    Usage:

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

提交回复
热议问题