ASP.NET QueryString without equals sign

2019-07-21 09:48发布

问题:

When I have a url like:

http://www.mysite.com/?MyTest=

MyTest shows up as a key in the querystring of the request object.

If I remove the = sign like:

http://www.mysite.com/?MyTest

It no longer shows up in the querystring keys (or AllKeys if you prefer).

How can I determine whether this key exists or not?

回答1:

This is quite odd behaviour, without the = sign the QueryString object returned by the Request has a Count of 1 with a value of MyTest and a key of null.
You could test the QueryString to see if it contains the value you are expecting:

if(Request.QueryString.ToString().Contains("MyTest"))
{
    // Do stuff
}

Edit: this answer gives a bit more explanation as to what is going on with keyless parameters (scroll past the accepted answer).



回答2:

I believe you can do Request.QueryString[null] or Request.QueryString.GetValues(null).


Without the equal sign MyTest is no longer a key, but a key-less value, you use null to get those. To check for both cases do this:

bool myTestPresent = Request.QueryString["MyTest"] != null
   || Request.QueryString.GetValues(null).Contains("MyTest", StringComparer.OrdinalIgnoreCase);


回答3:

You shoul use ToString() function

if (Request.QueryString.ToString() == "MyTest")
{
 //do something
}