16

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!

2
  • 1
    If at all possible, don't try to provide information in that manor. Either ensure that the caller sets a value to a query parameter to pass information through a query parameter, or if it doesn't make sense as a key/value pair then instead manipulate the query in another way. Having a query parameter with no value adding information is going to be confusing to those using the site. Commented Dec 31, 2013 at 16:06
  • That makes good sense to me. I may not be able to change the URL though, since I didn't create it in the first place and my supervisor uses it for stats and such. I'll ask him if he's okay with switching it to a 'query=true' type query string. Commented Dec 31, 2013 at 16:25

9 Answers 9

10

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")
Sign up to request clarification or add additional context in comments.

2 Comments

This works fine you just need to check for null after get values
Note to myself and others: this is not the same as Request.QueryString[null].Contains("query"), which will return True on www.site.com/index?notmyquery. Request.QueryString[null] returns a comma-delimited string, while Request.QueryString.GetValues(null) returns a string array.
8

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

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

1 Comment

This is the best answer, as it doesn't break on www.site.com/index?query=.
5

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.

2 Comments

Neither of these seems to work. The AllKeys collection does return with a 1 Count, meaning the query string is in there, but the lambda expression can't find the key. It seems to be looking for the value?
Ah, figured it out. Your code works if the query string has a value. Otherwise the key shows up as null. Similar to what Grant said in his answer.
4

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.

8 Comments

This is actually the answer. I can't check for a specific key unless the key has a value. I'm not comfortable checking for a null key in AllKeys and just leaving it at that, so I'll have to add a value, as per Servy's comment.
@Emad Then upvote it if you found it useful. Why leave a comment on other answers?
I did up vote but usually people look straight to the answer marked as correct. I wanted everyone to see that there are other options. Your answer is right but in my opinion not the best. I even posted a modified answer myself.
This answer is wrong. If query was included as a parameter, but no value was specified, then the value of query will be null and the key will be null as well in Request.QueryString.AllKeys
@Cesar It helped a few people including the OP, at least. I can't unaccept it as the "best answer" for the OP. If another answer is better, I'd suggest upvoting it so it gets more visibility.
|
3

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
}

Comments

2

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

1 Comment

Your fiddle has nothing to do with the answer.
0

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
}

Comments

0

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

Comments

-1

I Prefer to use:

If(Request.QueryString.AllKeys.Contains("query")
{
    //
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.