19

Within the context of an ASP.NET page, I can use Request.QueryString to get a collection of the key/value pairs in the query string portion of the URI.

For example, if I load my page using http://local/Default.aspx?test=value, then I can call the following code:

//http://local/Default.aspx?test=value

protected void Page_Load(object sender, EventArgs e)
{
    string value = Request.QueryString["test"]; // == "value"
}

Ideally what I want to do is check to see if test exists at all, so I can call the page using http://local/Default.aspx?test and get a boolean telling me whether test exists in the query string. Something like this:

//http://local/Default.aspx?test

protected void Page_Load(object sender, EventArgs e)
{
    bool testExists = Request.QueryString.HasKey("test"); // == True
}

So ideally what I want is a boolean value that tell me whether the test variable is present in the string or not.

I suppose I could just use regex to check the string, but I was curious if anybody had a more elegant solution.

I've tried the following:

//http://local/Default.aspx?test

Request.QueryString.AllKeys.Contains("test"); // == False  (Should be true)
Request.QueryString.Keys[0];                  // == null   (Should be "test")
Request.QueryString.GetKey(0);                // == null   (Should be "test")

This behavior is different than PHP, for example, where I can just use

$testExists = isset($_REQUEST['test']); // == True
4
  • 1
    Why can't you just check for a null? If(Request.QueryString["test"] != null)
    – JonH
    Feb 15, 2013 at 19:40
  • 1
    @JonH: Because Request.QueryString["test"] returns null whether test is present in the query string or not. Feb 15, 2013 at 19:43
  • huh? I'm not sure what you mean, it will only return == null if it doesn't see test in the query string otherwise it returns != null, and if thats the case you can grab the value of test. I dont see the issue.
    – JonH
    Feb 15, 2013 at 19:44
  • 2
    @JonH: I don't want to check the value of test, only to see if it exists. For example, I want ?test and test=anyvalue to both return true, but anything else (?differentkey=anyvalue) to return false. Feb 15, 2013 at 19:47

6 Answers 6

28

Request.QueryString.GetValues(null) will get a list of keys with no values

Request.QueryString.GetValues(null).Contains("test") will return true

8
  • 1
    You just beat me by a few seconds :-) I had to peek into the sourcecode to discover this curious behavior. Feb 15, 2013 at 19:52
  • i get a System.ArgumentNullException: Value cannot be null. error with this. Sep 28, 2013 at 8:13
  • 1
    To avoid ArgumentNullException use this: if (Request.QueryString.Count > 0 && Request.QueryString.GetValues(null).Contains("test"))
    – jurev
    Feb 6, 2014 at 15:43
  • 2
    For the code above, be aware that this will work for any query having "test" inside. Ex: "?hello=test. If you want to be more specific use this: Request.QueryString.ToString().Split('&').Any(x => x.Split('=')[0] == "test") Jun 4, 2014 at 18:35
  • 1
    To remove the NRE you could use (Request.QueryString.GetValues(null) ?? new string[0]).Contains(key) I'd wrap this in an extension method similar to @DarkDaskin's answer Sep 23, 2014 at 18:23
5

I wrote an extension method to solve this task:

public static bool ContainsKey(this NameValueCollection collection, string key)
{
    if (collection.AllKeys.Contains(key)) 
        return true;

     // ReSharper disable once AssignNullToNotNullAttribute
    var keysWithoutValues = collection.GetValues(null);
    return keysWithoutValues != null && keysWithoutValues.Contains(key);
}
1
  • +1 great answer. As of R#8 you no longer need the disable hint, it appears they updated their analysis of GetValues(null). One other thing I can point out, don't forget about the overload Contains(key, StringComparer.OrdinalIgnoreCase) to avoid case sensitivity. Sep 23, 2014 at 18:20
2

Request.QueryString is a NameValueCollection, but items are only added to it if the query string is in the usual [name=value]* format. If not, it is empty.

If your QueryString was of the form ?test=value, then Request.QueryString.AllKeys.Contains("test") would do what you want. Otherwise, you're stuck doing string operations on Request.Url.Query.

2

I use this.

if (Request.Params["test"] != null)
{
    //Is Set
}
else if(Request.QueryString.GetValues(null) != null && 
       Array.IndexOf(Request.QueryString.GetValues(null),"test") > -1)
{
    //Not set
}
else
{
    //Does not exist
}
1

TRY this one, it solved my issue! It will count either the query string has a value or empty and then you can check the required query string value with the Key.

  if (!Page.IsPostBack)
        {
           if (Request.QueryString.Count > 0)
            {
                if (Request.QueryString["departmentId"] != null)
                {
                    GetSurveyByDeptAndStatus(departmentId: Request.QueryString["departmentId"], status: "Not Surveyed");
                    rbListEmpsSurvey.Items[1].Selected = true;
                }

                else if (Request.QueryString["SurveyStatus"] != null)
                {
                    SatisfactionStatus = Request.QueryString["SurveyStatus"] "";
                    GetSurveyByDeptAndStatus(status: SatisfactionStatus);
                    GetDepartments();
                }}}
-2
Request.QueryString.ToString().Contains("test")

This works in the special case where you're looking for a single querystring parameter, e.g. MyFile.aspx?test

For more complex, general, cases then other solutions would be better.

7
  • 1
    Hmmm... it could work, but it's not very reliable; it wouldn't pass a decent unit test. The accepted answer is still the best. I wanted to see if the query string contained a variable called test (whether or not it contained a value - for example: ?test or ?test=anyvalue both return true). Checking to see if the string test exists anywhere in the querystring could produce false positives. For example: ?a=test - the variable name is a, which is not what I'm looking for. Also ?bestest=10 would produce a false positive. Nov 1, 2013 at 18:30
  • Good point although for my Use Case it was fine. I suppose one could throw a regex at the raw querystring.
    – GlennG
    Nov 3, 2013 at 20:25
  • 1
    Example regex: (?<!=)(\btest\b)(=?|&|$)
    – GlennG
    Nov 3, 2013 at 21:21
  • 1
    Example test querystring (which the regex matches the three correct cases): test&aaa=tester&test1=test&mytest=test&test&xxxxx&test=test
    – GlennG
    Nov 3, 2013 at 21:22
  • Yea you could use regex to parse HTML too. ;-) codinghorror.com/blog/2008/06/… Nov 4, 2013 at 2:36

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.