Stephen Sulzberger’s Blog

January 20, 2008

asp.net: Modify Request.QueryString

Filed under: .net,asp.net,C# — Stephen @ 4:30 pm

Suppose you needed to modify the query string passed in a given URL before redirecting to another (or even the same) page. For example, imagine you needed to take:

/default.aspx?name1=value1&name2=value2&color=red

and turn it into something like:

/default.aspx?name1=valueX&name2=valueY&colorcode=red

I’ve seen this done with loops, new URI’s, and so on to get around the query string read-only “problem”, but most implementations like these are fairly arduous, not to mention error-prone. Given all of the idiosyncrasies involved with the Request.QueryString object (e.g. is read-only, is a modified version of the NameValueCollection object, etc.), I still think the the following approach is the best bet:

using System.Collections.Specialized;

public partial class ModifyQueryStringExample : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    // Create a new (editable) NameValueCollection using the existing (read-only) collection
    NameValueCollection objNewValueCollection = HttpUtility.ParseQueryString(Request.QueryString.ToString());
    objNewValueCollection.Set("name1", "valueX");
    objNewValueCollection.Set("name2", "valueY");
    objNewValueCollection.Add("colorcode", objNewValueCollection.Get("color"));
    objNewValueCollection.Remove("color");

    string sRedirect = Request.Url.AbsolutePath;
    string sNewQueryString = "?" + objNewValueCollection.ToString();

    sRedirect = sRedirect + sNewQueryString;

    Response.Redirect(sRedirect, true);
  }
}

Some notes:

  1. All other parameters passed in by the original query string will be carried over untouched. For example, if the original query string also included something like “id=1234&status=1”, these values would persist into the new redirect even while the other name/value pairs have been modified.    
  2. The NameValueCollection Set() method allows nulls, so it will work regardless of whether or not the key you’re looking for actually exists. If the key exists, the value will be appended accordingly. If the key does not exist, it will be added with the appropriate value. This time around I chose to use the Add() method for readability since I know for a fact that this routine will always be adding a key (“colorcode”) rather than appending one.
  3. All NameValueCollection methods that use a text compare are case-insensitive, as per msdn: http://msdn2.microsoft.com/en-us/library/system.collections.specialized.namevaluecollection.namevaluecollection.aspx 
  4. The NameValueCollection ToString() method automatically inserts “=”/”&” characters for you when/where appropriate. The NameValueCollection instance returned by HttpUtility.ParseQueryString is an HTTPValueCollection (a specialized NameValueCollection type), so its ToString() method will automatically insert “=”/”&” characters for you where appropriate. Although this is undoubtedly a nice feature, one can’t help but mention that the surprisingly convenient behavior just described is not immediately obvious given the msdn documentation at http://msdn.microsoft.com/en-us/library/system.web.httputility.parsequerystring.aspx. Nevertheless, the implementation is made clear by evaluating any NameValueCollection.ToString() against an HTTPValueCollection.ToString(). The former will return the object’s string representation (‘System.Collections.Specialized.NameValueCollection’) while the latter, of course, will provide a legitimate name/value collection with the applicable field-value separators. Interestingly, the only way to get an HTTPValueCollection instance in the first place is to use HttpUtility.ParseQueryString. No doubt a quirky matter. For further discussion on the issue, visit http://msmvps.com/blogs/paulomorgado/archive/2008/07/15/make-the-httpvaluecollection-class-public-and-move-it-to-system-dll.aspx               

Blog at WordPress.com.