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
Request.QueryString.GetValues(null)
will get a list of keys with no values
Request.QueryString.GetValues(null).Contains("test")
will return true
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
}
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);
}
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.
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
.