20

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) Commented Feb 15, 2013 at 19:40
  • 1
    @JonH: Because Request.QueryString["test"] returns null whether test is present in the query string or not. Commented 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. Commented 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. Commented Feb 15, 2013 at 19:47

7 Answers 7

28

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

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

Sign up to request clarification or add additional context in comments.

8 Comments

You just beat me by a few seconds :-) I had to peek into the sourcecode to discover this curious behavior.
i get a System.ArgumentNullException: Value cannot be null. error with this.
To avoid ArgumentNullException use this: if (Request.QueryString.Count > 0 && Request.QueryString.GetValues(null).Contains("test"))
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")
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
|
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 Comment

+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.
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.

Comments

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
}

Comments

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

Comments

1

Visual Basic Solution

Request.QueryString.GetValues(vbNullString).Contains("test")

Although @Joe's answer is the correct answer, it doesn't account for VB.net programmers. The VB issue with @Joe's [correct] answer is that it yields an error at the "GetValues(null)" section. vbNullString alleviates the issue.


Additional Note

ClientQueryString.Contains("test")

might solve your problem (it did for me). Please know, though, that this solution has its pitfalls.


Summary for VB Programmers

Either of these will [probably] get the job done for you:

  1. Request.QueryString.GetValues(vbNullString).Contains("test")
  2. ClientQueryString.Contains("test")

I would've added this as a comment, but I don't have enough reputation points (43 out of 50)

Comments

-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 Comments

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.
Good point although for my Use Case it was fine. I suppose one could throw a regex at the raw querystring.
Example regex: (?<!=)(\btest\b)(=?|&|$)
Example test querystring (which the regex matches the three correct cases): test&aaa=tester&test1=test&mytest=test&test&xxxxx&test=test
Yea you could use regex to parse HTML too. ;-) codinghorror.com/blog/2008/06/…
|

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.