Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 412
Chris Avatar asked Jul 27 '09 13:07

Chris


People also ask

How do you clear a query string?

The only way to 'clear' the query string is to do a redirect to the same URL but without the query string part. Is there particular reason why you want it cleared? If security is the issue, try using a POST call instead or encrypt the query string.

What is query string parse?

The querystring. parse() method is used to parse a URL query string into an object that contains the key and pair values of the query URL. The object returned does not inherit prototypes from the JavaScript object, therefore usual Object methods will not work.

What is query string in JavaScript?

A query string is part of the full query, or URL, which allows us to send information using parameters as key-value pairs.

How do you make a string query?

An easy way to build a query string in Javascript is to use a URLSearchParams object: var query = new URLSearchParams(); query. append("KEY", "VALUE");


1 Answers

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

like image 130
Rob Levine Avatar answered Oct 05 '22 21:10

Rob Levine