Question

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!

Was it helpful?

Solution

If you do not specify a value, the key will be automatically set to null, so you cannot check its existence.

In order to check if the value actually exists, you can check in the collection of Values equalling null if it contains your Key:

Request.QueryString.GetValues(null).Contains("query")

OTHER TIPS

It returns null because in that query string it has no value for that key. I think the check you're looking for is this:

if(Request.QueryString.Keys.OfType<string>().Any(k => k == "query"))

or even:

if(Request.QueryString.AllKeys.Any(k => k == "query"))

The latter is probably more appropriate because that array is already cached.

this is the fastest way to check it thanks to Ludovic's answer

if(Request.QueryString.GetValues(null)?.Contains("query")??false)

If query was included as a parameter, but no value was specified, then the value of query will be null but it will still exist in Request.QueryString.AllKeys.

If query was not included, it won't exist in Request.QueryString.AllKeys at all.

Ludovic has the right answer. But I would like to offer a more robust version.

var valueEntries = Request.QueryString.GetValues((string)null) ?? new string[] {};
if (valueEntries.Contains("query", StringComparer.OrdinalIgnoreCase))
{
    // value is specify in querystring
}
else
{
    // value is NOT specify in querystring
}

This is verbose and it works. Here is a .NET Fiddle.

@using System.Linq;

@{
    var empties = Request.Url.Query
        .Split('&')
        .Where(s => !s.Contains("=") || s.Last() == '=');

    var keyExistsAndIsEmpty = empties.Any(x => x.Contains("target-key")
}

It turns out that if the value is null, then the key is also null in the QueryString collection. Your best bet is simply to assign a value to the query. There might be a way for you to rename the parameter so that this makes more semantic sense. For example instead of www.site.com/index?getdocument=yes you could do www.site.com/index?action=getdocument

However if you still want the url www.site.com/index?query to work, there is a way: don't use the QueryString at all and parse the URL manually:

string query = Request.RawUrl.Split('?')[1];
if (query == "query")
{
    // send the data
}

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

I Prefer to use:

If(Request.QueryString.AllKeys.Contains("query")
{
    //
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top