A clean way to generate QueryString parameters for web queries

I ran into a problem in my current application that required messing with the query string in the base class Page(which all my pages inherit) 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 easy manipulation of the query string.

Code example:

// 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
source share
6 answers

Use HttpUtility.ParseQueryStringas someone suggested (and then deleted).

, HttpValueCollection, NameValueCollection ( , ). / ( /) ToString -, , HttpValueCollection ToString, .

+4

, , . ( , , , ).

, : ( , )

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

uri:

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

:

"http://www.google.com/somepage"
"http://www.google.com/somepage?"
"http://www.google.com/somepage?OldQuery=Data"
"http://www.google.com/somepage?OldQuery=Data&"
+4

: , - Uri.EscapeDataString :

string s = string.Format("http://somesite?foo={0}&bar={1}",
            Uri.EscapeDataString("&hehe"),
            Uri.EscapeDataString("#mwaha"));
+2

, , . QueryString.

() ( ) .

, Asp.Net , , trailing .s.

0

!!!

// 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());
   }
}
0
source

I find my way to easily manipulate using 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)
0
source

All Articles