Skip to content

Get URL without query string in C#

Sometimes you may need to ignore the query params in a URL. You can use the following code snippets to retrieve the URL without the query string.

Advertisements

Method 1 : Retrieve the left part of the URL using GetLeftPart

Request.Url.GetLeftPart(UriPartial.Path)

Example:

// Create Uri
Uri uriAddress = new Uri("http://www.poopcode.com/index.htm#search");
Console.WriteLine(uriAddress.Fragment);
Console.WriteLine("Uri {0} the default port ", uriAddress.IsDefaultPort ? "uses" : "does not use");
 
Console.WriteLine("The path of this Uri is {0}", uriAddress.GetLeftPart(UriPartial.Path));
Console.WriteLine("Hash code {0}", uriAddress.GetHashCode());
// The example displays the following output:
//        #search
//        Uri uses the default port
//        The path of this Uri is http://www.poopcode.com/index.htm
//        Hash code -988419291

Method 2 : Using Substring

Advertisements
string url = "http://www.poopcode.com/order.aspx?value1=123&value2=orderid";
string path = url.Substring(0, url.IndexOf("?"));

Method 3: Using split

string url = "http://www.poopcode.com/order.aspx?value1=123&value2=orderid";
string path = url.split('?')[0];

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.