Lee Kelleher

Making Request.QueryString writable (by clone/copy)

Posted on . Estimated read time: under a minute (102 words)

Every now and then I completely forget that the Request.QueryString (and Request.Form) object is read-only. Today I had a bit of functionality where I needed to remove a key/value from the collection - but the Remove() method (of the NameValueCollection object) throws an exception.

Unfortunately, the Request.QueryString's CopyTo method assigns the values to an ARRAY, not a NameValueCollection - losing functionality and flexibility.

You need to copy the Request.QueryString object to a new NameValueCollection instance, here's how:

NameValueCollection qs = new NameValueCollection(Request.QueryString);

Now you can add/remove the key/values to your hearts content!

Oh, yeah, remember to import the System.Collections.Specialized namespace too!