Search code examples
c#asp.net.net-3.5

Check if unassigned variable exists in Request.QueryString


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

Solution

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

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