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

Chris picture Chris · Jul 27, 2009 · Viewed 42.2k times · Source

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?

Answer

Rob Levine picture Rob Levine · Jul 27, 2009

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