Check if non-valued query string exists in url with C#

Viewed 29080

I've seen a couple examples of how to check if a query string exists in a url with C#:

www.site.com/index?query=yes

if(Request.QueryString["query"]=="yes")

But how would I check a string without a parameter? I just need to see if it exists.

www.site.com/index?query

if(Request.QueryString["query"] != null) //why is this always null?

I know there's probably a simple answer and I'll feel dumb, but I haven't been able to find it yet. Thanks!

9 Answers

You cannot use a null check to determine if a key exists when the "=" is not supplied since null means that the key wasn't in the query string.

The problem is that "query" is being treated as a value with a null key and not as a key with a null value.

In this case the key is also null inside Request.QueryString.AllKeys.

I used this generic method to "fix" the null key problem in the query string before using it. This doesn't involve manually parsing the string.

Usage example:

var fixedQueryString = GetFixedQueryString(Request.QueryString);
if (fixedQueryString.AllKeys.Contains("query"))
{
}

The method:

public static NameValueCollection GetFixedQueryString(NameValueCollection originalQueryString)
{
      var fixedQueryString = new NameValueCollection();

      for (var i = 0; i < originalQueryString.AllKeys.Length; i++)
      {
          var keyName = originalQueryString.AllKeys[i];

          if (keyName != null)
          {
              fixedQueryString.Add(keyName, originalQueryString[keyName]);
          }
          else
          {                       
              foreach (var keyWithoutValue in originalQueryString[i].Split(','))
              {
                  fixedQueryString.Add(keyWithoutValue, null);
              }              
          }
      }

      return fixedQueryString;
}
Related