代码改变世界

ASP.NET 中Request.QueryString 中的key

2014-01-03 23:46  Shawn.Cheng  阅读(1184)  评论(0编辑  收藏  举报

在ASP.net中 的Key是可能为null的,例如在如下的Url中
http://localhost:14546/Home/Index?a
有一个key=null 其value是a,以前一直以为key=a value=空串。经过实际测法,发现其实并不是这样。
如果url=http://localhost:14546/Home/Index?a=1&b 那么存在一个key=null和value=b的键值对
如果url=http://localhost:14546/Home/Index?a=1&b& 那么就存在一个key=null,value=b 以及一个value=空串的键值对。

测试程序如下(mvc的)

1 public ActionResult Index()
2 {
3 return View();
4 }
 1 @{
 2 ViewBag.Title = "Index";
 3 }
 4 <style>
 5 table {
 6 width:500px;
 7 border-collapse: collapse;
 8 }
 9 th,td {
10 border: 1px solid black;
11 }
12 th {
13 background-color:#efefef;
14 }
15 </style>
16 <h2>Index</h2>
17 
18 @{
19 Func<string, string> render = (value) =>
20 {
21 if (value == null)
22 return "NULL";
23 
24 if (string.IsNullOrEmpty(value))
25 return "EMPTY";
26 
27 return value;
28 };
29 }
30 <table>
31 <tr>
32 <th> key</th>
33 <th> value</th>
34 </tr>
35 @foreach (var key in Request.QueryString.AllKeys)
36 {
37 <tr>
38 <td>@render(key)</td>
39 <td>@render(Request.QueryString[key])</td>
40 </tr>
41 }
42 </table>

输入http://localhost:14546/Home/Index?a

KEY Value
NULL a

 

 

输入http://localhost:14546/Home/Index?a=1&

Key value
a 1
NULL EMPTY

 

 

 

输入http://localhost:14546/Home/Index?a&b

Key value
null a,b