views:

1537

answers:

6

I came across a problem in my current application that required fiddling with the query string in a base Page class (which all my pages inherit from) to solve the problem. Since some of my pages use the query string I was wondering if there is any class that provides clean and simple query string manipulation.

Example of code:

// What happens if I want to future manipulate the query string elsewhere
// (e.g. maybe rewrite when the request comes back in)
// Or maybe the URL already has a query string (and the ? is invalid)

Response.Redirect(Request.Path + "?ProductID=" + productId);
+3  A: 

Use HttpUtility.ParseQueryString, as someone suggested (and then deleted).

This will work, because the return value from that method is actually an HttpValueCollection, which inherits NameValueCollection (and is internal, you can't reference it directly). You can then set the names/values in the collection normally (including add/remove), and call ToString -- which will produce the finished querystring, because HttpValueCollection overrides ToString to reproduce an actual query string.

technophile
The ParseQueryString will only take the query string part of a URL (not the path) and it will not prefix it with a question mark.
Y Low
And? It's trivial to pull the querystring out of a URL (for example, using the System.Uri class, or a simple string.Split or string.Substring), and once you have it, you know it can't internally contain question marks (they'd be encoded), so simply do url + "?" + queryString.ToString().
technophile
+3  A: 

I was hoping to find a solution built into the framework but didn't. (those methods that are in the framework require to much work to make it simple and clean)

After trying several alternatives I currently use the following extension method: (post a better solution or comment if you have one)

public static class UriExtensions
{
    public static Uri AddQuery(this Uri uri, string name, string value)
    {
        string newUrl = uri.OriginalString;

        if (newUrl.EndsWith("&") || newUrl.EndsWith("?"))
            newUrl = string.Format("{0}{1}={2}", newUrl, name, value);
        else if (newUrl.Contains("?"))
            newUrl = string.Format("{0}&{1}={2}", newUrl, name, value);
        else
            newUrl = string.Format("{0}?{1}={2}", newUrl, name, value);

        return new Uri(newUrl);
    }
}

This extension method makes for very clean redirection and uri manipulation:

Response.Redirect(Request.Url.AddQuery("ProductID", productId).ToString());

// Will generate a URL of www.google.com/search?q=asp.net
var url = new Uri("www.google.com/search").AddQuery("q", "asp.net")

and will work for the following Url's:

"http://www.google.com/somepage"
"http://www.google.com/somepage?"
"http://www.google.com/somepage?OldQuery=Data"
"http://www.google.com/somepage?OldQuery=Data&"
Y Low
technophile
+1  A: 

Note that whatever route you use, you should really encode the values - Uri.EscapeDataString should do that for you:

string s = string.Format("http://somesite?foo={0}&bar={1}",
            Uri.EscapeDataString("&hehe"),
            Uri.EscapeDataString("#mwaha"));
Marc Gravell
What about Server.UrlEncode ?
Y Low
Yes, that'll do the job too since you are in asp.net. In the more general sense, you might not have (or be able to have, in some cases, like Silverlight / CF / Client Profile) a reference to System.Web.dll - but fine in this case.
Marc Gravell
A: 

What I usually do is just rebuild the querystring. Request has a QueryString collection.

You can iterator over that to get the current (unencoded) parameters out, and just join them together (encoding as you go) with the appropriate separators.

The advantage is that Asp.Net has done the original parsing for you, so you don't need to worry about edge cases such as trailing & and ?s.

Phil Nash
A: 

Check This!!!

// First Get The Method Used by Request i.e Get/POST from current Context

string method = context.Request.HttpMethod;

// Declare a NameValueCollection Pair to store QueryString parameters from Web Request

NameValueCollection queryStringNameValCollection = new NameValueCollection();

// Web Request Method is Post

if (method.ToLower().Equals("post"))
{ string contenttype = context.Request.ContentType;

if (contenttype.ToLower().Equals("application/x-www-form-urlencoded"))

{

  int data = context.Request.ContentLength;

  byte[] bytData = context.Request.BinaryRead(context.Request.ContentLength);

  queryStringNameValCollection = context.Request.Params;

}

}

// Web Request Method is Get

else

{

queryStringNameValCollection = context.Request.QueryString;

}

// Now Finally if you want all the KEYS from QueryString in ArrayList

ArrayList arrListKeys = new ArrayList();

for (int index = 0; index < queryStringNameValCollection.Count; index++)

{

string key = queryStringNameValCollection.GetKey(index);

if (!string.IsNullOrEmpty(key))

{

  arrListKeys.Add(key.ToLower());

}

}

NSK