ASP.NET QueryString without equals sign

蹲街弑〆低调 提交于 2019-12-24 02:25:13

问题


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
}


来源:https://stackoverflow.com/questions/9621562/asp-net-querystring-without-equals-sign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!