3

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);

6 Answers 6

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
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().
4

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&"

1 Comment

What happens if either name or value has an illegal character (such as a ? or &) in it? And using System.Uri but doing your own parsing instead of using the Query property is kind of pointless.
2

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"));

1 Comment

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.
0

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.

Comments

0

I find my way for easy manipulating with get parameters.

public static string UrlFormatParams(this string url, string paramsPattern, params object[] paramsValues)
{
    string[] s = url.Split(new string[] {"?"}, StringSplitOptions.RemoveEmptyEntries);
    string newQueryString = String.Format(paramsPattern, paramsValues);
    List<string> pairs = new List<string>();

    NameValueCollection urlQueryCol = null;
    NameValueCollection newQueryCol = HttpUtility.ParseQueryString(newQueryString);

    if (1 == s.Length)
    {
        urlQueryCol = new NameValueCollection();
    }
    else
    {
        urlQueryCol = HttpUtility.ParseQueryString(s[1]);
    }



    for (int i = 0; i < newQueryCol.Count; i++)
    {
        string key = newQueryCol.AllKeys[i];
        urlQueryCol[key] = newQueryCol[key];
    }

    for (int i = 0; i < urlQueryCol.Count; i++)
    {
        string key = urlQueryCol.AllKeys[i];
        string pair = String.Format("{0}={1}", key, urlQueryCol[key]);
        pairs.Add(pair);
    }

    newQueryString = String.Join("&", pairs.ToArray());

    return String.Format("{0}?{1}", s[0], newQueryString);
}

Use it like

"~/SearchInHistory.aspx".UrlFormatParams("t={0}&s={1}", searchType, searchString)

Comments

0

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();

if (method.ToLower().Equals("post")) // Web Request Method is 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;
   }
}
else // Web Request Method is Get
{
   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());
   }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.