Check if unassigned variable exists in Request.QueryString
Asked Answered
T

6

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
Traction answered 15/2, 2013 at 19:36 Comment(4)
Why can't you just check for a null? If(Request.QueryString["test"] != null)Kowalewski
@JonH: Because Request.QueryString["test"] returns null whether test is present in the query string or not.Traction
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.Kowalewski
@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.Traction
P
28

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

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

Pfosi answered 15/2, 2013 at 19:50 Comment(8)
You just beat me by a few seconds :-) I had to peek into the sourcecode to discover this curious behavior.Hatley
i get a System.ArgumentNullException: Value cannot be null. error with this.Telencephalon
I also get the error System.ArgumentNullException: Value cannot be null.Glade
I can only verify that in .Net 4.5 this is still working for me ? Request.QueryString.GetValues(null).Contains("blah") false ? Request.QueryString.GetValues(null).Contains("foo") truePfosi
To avoid ArgumentNullException use this: if (Request.QueryString.Count > 0 && Request.QueryString.GetValues(null).Contains("test"))Coyne
This one ^ will crash when the QueryString is not empty and present. Use this instead: Request.QueryString.ToString().Contains("test"); // ToString will show all QueryStrings even if empty.Vernice
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")Vernice
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 answerPasserby
G
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);
}
Gentian answered 10/10, 2013 at 11:21 Comment(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.Passerby
Q
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.

Quentinquercetin answered 15/2, 2013 at 19:46 Comment(0)
I
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
}
Ish answered 14/1, 2016 at 17:53 Comment(0)
G
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();
                }}}
Grassland answered 18/2, 2021 at 10:37 Comment(0)
S
-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.

Sou answered 1/11, 2013 at 18:13 Comment(7)
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.Traction
Good point although for my Use Case it was fine. I suppose one could throw a regex at the raw querystring.Sou
Example regex: (?<!=)(\btest\b)(=?|&|$)Sou
Example test querystring (which the regex matches the three correct cases): test&aaa=tester&test1=test&mytest=test&test&xxxxx&test=testSou
Yea you could use regex to parse HTML too. ;-) codinghorror.com/blog/2008/06/…Traction
Thanks for the downvote. "local/Default.aspx?test" will be validated using Request.QueryString.ToString.Contains("test")Sou
Yep, remember I lose reputation too with a downvote. I already indicated that string matching would work in my original question: "I suppose I could just use regex to check the string, but I was curious if anybody had a more elegant solution". This answer is potentially misleading for the reasons I mentioned above. Also, you're missing parentheses after ToString. ;-)Traction

© 2022 - 2024 — McMap. All rights reserved.