Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify request querystring parameters to build a new link without resorting to string manipulation

I want to dynamically populate a link with the URI of the current request, but set one specific query string parameter. All other querystring paramaters (if there are any) should be left untouched. And I don't know in advance what they might be.

Eg, imagine I want to build a link back to the current page, but with the querystring parameter "valueOfInterest" always set to be "wibble" (I'm doing this from the code-behind of an aspx page, .Net 3.5 in C# FWIW).

Eg, a request for either of these two:

/somepage.aspx
/somepage.aspx?valueOfInterest=sausages

would become:

/somepage.aspx?valueOfInterest=wibble

And most importantly (perhaps) a request for:

/somepage.aspx?boring=something
/somepage.aspx?boring=something&valueOfInterest=sausages

would preserve the boring params to become:

/somepage.aspx?boring=something&valueOfInterest=wibble

Caveats: I'd like to avoid string manipulation if there's something more elegant in asp.net that is more robust. However if there isn't something more elegant, so be it.

I've done (a little) homework: I found a blog post which suggested copying the request into a local HttpRequest object, but that still has a read-only collection for the querystring params. I've also had a look at using a URI object, but that doesn't seem to have a querystring

like image 838
Andrew M Avatar asked Apr 06 '10 14:04

Andrew M


1 Answers

This will work as long as [1] you have a valid URL to begin with (which seems reasonable) [2] you make sure that your new value ('sausages') is properly escaped. There's no parsing, the only string manipulation is to concatenate the parameters.

Edit

Here's the C#:

    UriBuilder u = new UriBuilder(Request.Url);
    NameValueCollection nv = new NameValueCollection(Request.QueryString);

    /* A NameValueColllection automatically makes room if this is a new
       name. You don't have to check for NULL.
     */
    nv["valueOfInterest"] = "sausages";

    /* Appending to u.Query doesn't quite work, it
       overloaded to add an extra '?' each time. Have to 
       use StringBuilder instead.
    */
    StringBuilder newQuery = new StringBuilder();
    foreach (string k in nv.Keys)
        newQuery.AppendFormat("&{0}={1}", k, nv[k]);

    u.Query = newQuery.ToString();
    Response.Redirect(u.Uri.ToString());
like image 184
egrunin Avatar answered Oct 27 '22 01:10

egrunin