Manipulating Request.QueryString

The Request.QueryString property is declared as System.Collections.Specialized.NameValueCollection but the internal implementation is really a derived (undocumented) class called System.Web.HttpValueCollection.

You can access each query string parameter using the index operator [], but you cannot modify the parameter values or add or delete a parameter from the collection:

var q = Request.QueryString;
// => read-only System.Web.HttpValueCollection
if (q["param"] == null)
  q.Add("param", "some-value");

This code will throw a System.NotSupportedException.

Why do you want to manipulate the query string anyway? Say you have a request and you want to add/change/remove a parameter of the query string, and then redirect to the modified URL. Of course, you want to make sure that each parameter is in the URL exactly once. Request.QueryString[] provides a simply mechanism to access and modify the parameters and their values.

To get a modifiable NameValueCollection from the current request, we need the helper method System.Web.HttpUtility.ParseQueryString (which again returns an HttpValueCollection):

var q = System.Web.HttpUtility.ParseQueryString(
if (q["param"] == null)
    q.Add("param", "some-value");
var r = Request.Path + "?" + q.ToString();

To redirect from the current request, we take the request’s Path and concatenate the collection’s ToString() result. The HttpValueCollection.ToString() adds ‘&’ and ‘=’ between parameters and their values (as opposed to NamedValueCollection.ToString() which just returns the class name).

One Response to Manipulating Request.QueryString

  1. Mark says:

    Many thanks

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: