如何Request客户端的传值的Data

我们在做B/S的项目,客户端向服务端传值的时候,一般都是request接受。

Request常用三个接受方式为:Request.QueryString,Request.Form,Request.Params

它们之间关系,很简单 ,我就不列举了。

我就贴下 一个我封装的示例代码:

    class Program
    {


        static void Main(string[] args)
        {
            //First Method
            string _id = string.Empty;
            string _prodctName = string.Empty;
            int _Price = 0;
            //IsNullOrWhiteSpace 代替IsNullOrEmpty 
            if (!string.IsNullOrWhiteSpace(HttpContext.Current.Request.QueryString["id"]))
            {
                _id = HttpContext.Current.Request.QueryString["id"];
            }
            if (!string.IsNullOrWhiteSpace(HttpContext.Current.Request.QueryString["prodctName"]))
            {
                _prodctName = HttpContext.Current.Request.QueryString["prodctName"];
            }
            if (!string.IsNullOrWhiteSpace(HttpContext.Current.Request.Params["Price"]))
            {
                _Price = int.Parse(HttpContext.Current.Request.QueryString["Price"]); //很危险哦 很容易就报错
            }

            //two Method 
            // 我最常用的方法 利用委托和扩展方法 进行组合链式
            //这里可以封装到一个方法里
            Func<string, string> GetRequest = (string s) =>
            {
                var str=HttpContext.Current.Request.QueryString[s];
                if (!string.IsNullOrWhiteSpace(str))
                {
                    return str;
                }
                else
                    return "";
            };

            _id = GetRequest("id");
            _prodctName = GetRequest("prodctName");
            _Price = GetRequest("price").FormatInt(); 

            //third Method
            //这里不做代码展示 一般用AJAX上 大致步骤如下
            //1.前台用做一个JSON对象传递到后台,拒绝细粒度传值,细粒度一般在传参少于三个以下, 超过三个都用粗粒度传值 
            //2.后台用json.net 进行反格式到model上 

            //four Method 
            //这里是我现在真打算运用项目中,性能和可行性还在测试中,等成功 我就更新出来 
            //希望能抛砖引玉,谢谢
        }
    }

    public static class FormatData
    {
        public static string FormatString(this string s)
        {
            return s.Replace("猴子吃香蕉","猴子吃菠萝");
        }
        public static int FormatInt(this string s)
        {
            //默认-100 如果-100表示格式化出错  约定一个准则就可以
            var _tempData = -100;
            int.TryParse(s, out _tempData);
            return _tempData;
        }
        //后面还有很多 如 日期 浮点型 过滤SQL非法字符等等
    }

 

posted on 2013-08-14 11:35  ~紫鱼~  阅读(1441)  评论(0编辑  收藏  举报