ASP.NET 1.1 中 QueryString 的安全获取写法

 1 ExpandedBlockStart.gif ContractedBlock.gif public   class  Util  dot.gif {
 2ExpandedSubBlockStart.gifContractedSubBlock.gif  private Util() dot.gif{}
 3InBlock.gif
 4InBlock.gif  // 从 querystring 集合中安全的取得一个 string. (总是不会有 null,所以叫做 'Safe')
 5ExpandedSubBlockStart.gifContractedSubBlock.gif  public static string GetStringSafeFromQueryString(Page page, string key) dot.gif{
 6InBlock.gif    string value = page.Request.QueryString[key];
 7InBlock.gif    return (value == null? string.Empty : value;
 8ExpandedSubBlockEnd.gif  }

 9InBlock.gif  
10InBlock.gif  // 在上述基础上,实现几个常用类型的获取方法。
11ExpandedSubBlockStart.gifContractedSubBlock.gif  public static int GetInt32SafeFromQueryString(Page page, string key, int defaultValue) dot.gif{
12InBlock.gif    string value = GetStringSafeFromQueryString(page, key);
13InBlock.gif    int i = defaultValue;
14ExpandedSubBlockStart.gifContractedSubBlock.gif    try dot.gif{
15InBlock.gif      i = int.Parse(value);
16ExpandedSubBlockStart.gifContractedSubBlock.gif    }
 catch dot.gif{}
17InBlock.gif    return i;
18ExpandedSubBlockEnd.gif  }

19InBlock.gif  // double 的实现
20InBlock.gif  public static double GetDoubleSafeFromQueryString(Page page,
21ExpandedSubBlockStart.gifContractedSubBlock.gif    string key, double defaultValue) dot.gif{
22InBlock.gif    string value = GetStringSafeFromQueryString(page, key);
23InBlock.gif    double d = defaultValue;
24ExpandedSubBlockStart.gifContractedSubBlock.gif    try dot.gif{
25InBlock.gif      d = double.Parse(value);
26ExpandedSubBlockStart.gifContractedSubBlock.gif    }
 catch dot.gif{}
27InBlock.gif    return d;
28ExpandedSubBlockEnd.gif  }

29InBlock.gif  // 同理可以写出 float,  的实现
30ExpandedBlockEnd.gif}
在我的任何页面里面,要获取 querystring 的时候,只要这样就可以了:
比如我要获取一个 string:
1 None.gif string  name  =  Util.GetStringSafeFromQueryString( this " name " );
2 ExpandedBlockStart.gifContractedBlock.gif if  (name.Length  >   0 dot.gif {
3InBlock.gif  // 进行正常的处理
4ExpandedBlockStart.gifContractedBlock.gif}
  else   dot.gif {
5InBlock.gif  // 不处理。
6ExpandedBlockEnd.gif}
获取 int:
int  id  =  Util.GetInt32SafeFromQueryString( this " id " 0 );

转载于:https://www.cnblogs.com/zhangchenliang/archive/2008/01/01/1022362.html

猜你喜欢

转载自blog.csdn.net/weixin_34234823/article/details/93495956