Get url without querystring

前端 未结 18 2153
后悔当初
后悔当初 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:56

    Split() Variation

    I just want to add this variation for reference. Urls are often strings and so it's simpler to use the Split() method than Uri.GetLeftPart(). And Split() can also be made to work with relative, empty, and null values whereas Uri throws an exception. Additionally, Urls may also contain a hash such as /report.pdf#page=10 (which opens the pdf at a specific page).

    The following method deals with all of these types of Urls:

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

    Example Output:

    • null ---> empty
    • empty ---> empty
    • 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#hash ---> page.html

提交回复
热议问题