ASP.NET QueryString without equals sign

2019-07-21 10:21发布

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?

3条回答
Anthone
2楼-- · 2019-07-21 10:28

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楼-- · 2019-07-21 10:28

You shoul use ToString() function

if (Request.QueryString.ToString() == "MyTest")
{
 //do something
}
查看更多
Lonely孤独者°
4楼-- · 2019-07-21 10:45

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

查看更多
登录 后发表回答