Truncating Query String & Returning Clean URL C# ASP.net

I would like to take the original URL, truncate the query string parameters, and return a cleaned up version of the URL. I would like it to occur across the whole application, so performing through the global.asax would be ideal. Also, I think a 301 redirect would be in order as well.

ie.

in: www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media

out: www.website.com/default.aspx

What would be the best way to achieve this?


Solution 1:

System.Uri is your friend here. This has many helpful utilities on it, but the one you want is GetLeftPart:

 string url = "http://www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media";
 Uri uri = new Uri(url);
 Console.WriteLine(uri.GetLeftPart(UriPartial.Path));

This gives the output: http://www.website.com/default.aspx

[The Uri class does require the protocol, http://, to be specified]

GetLeftPart basicallys says "get the left part of the uri up to and including the part I specify". This can be Scheme (just the http:// bit), Authority (the www.website.com part), Path (the /default.aspx) or Query (the querystring).

Assuming you are on an aspx web page, you can then use Response.Redirect(newUrl) to redirect the caller.

Hope that helps

Solution 2:

Here is a simple trick

Dim uri = New Uri(Request.Url.AbsoluteUri)

dim reqURL = uri.GetLeftPart(UriPartial.Path)

Solution 3:

Here is a quick way of getting the root path sans the full path and query.

string path = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,"");