简体   繁体   中英

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

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!

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

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.

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
}

由于Ludovic的回答,这是检查它的最快方法

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM