Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputting a manipulated QueryString in C#

Tags:

Using the following code I get a nice formatted string:

Request.QueryString.ToString 

Gives me something like: &hello=world&microsoft=sucks

But when I use this code to clone the collection to another object (of the same type) I get the Type() back from the ToString() method instead.

System.Collections.Specialized.NameValueCollection variables = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (!string.IsNullOrEmpty(variables["sid"]))
    variables.Remove("sid");
Response.Write(variables.ToString());

Is there a tidier way to output it rather than looking and building the string manually?

like image 281
Anthony Main Avatar asked Oct 23 '08 14:10

Anthony Main


4 Answers

HttpValueCollection is internal, but you can use "var" to declare it without extract it with reflector.

var query = HttpUtility.ParseQueryString(Request.Url.Query);
query["Lang"] = myLanguage; // Add or replace param
string myNewUrl = Request.Url.AbsolutePath + "?" + query;
like image 102
Michele Bersini Avatar answered Sep 28 '22 04:09

Michele Bersini


You can also use Reflector to extract the HttpValueCollection class into your own, and use it then.

like image 20
Igal Tabachnik Avatar answered Sep 28 '22 04:09

Igal Tabachnik


Because it is actually a special NVC that is of type HTTPValueCollection. So when you call .ToString on it, it knows how to format it correctly.

like image 35
Brian Schmitt Avatar answered Sep 28 '22 03:09

Brian Schmitt


Why do you want to copy the QueryString collection into a new NameValueCollection?

    if (!string.IsNullOrEmpty(Request.QueryString["sid"]))
        Request.QueryString.Remove("sid");

Yes indeed, i am wrong, it is read only. So the essence is to use the Remove Method on your NameValuecollection:

System.Collections.Specialized.NameValueCollection variables = new System.Collections.Specialized.NameValueCollection(Request.QueryString);
if (!string.IsNullOrEmpty(variables["sid"]))
    variables.Remove("sid");
like image 39
Johannes Hädrich Avatar answered Sep 28 '22 03:09

Johannes Hädrich