首页 > Web开发 > 详细

服务器端接受Json数据的绑定实现

时间:2014-03-19 21:51:09      阅读:481      评论:0      收藏:0      [点我收藏+]

1、在方法参数前加上JsonRead<T>的泛型特性

 public ActionResult GetData([JsonRead(typeof(PostData))]PostData postData)

 

 

2、继承CustomModelBinder类:

bubuko.com,布布扣
public class JsonReadAttribute : CustomModelBinderAttribute
    {
        private Type type;
        public JsonReadAttribute(Type type)
        {
            this.type = type;
        }
        public override IModelBinder GetBinder()
        {
            return new JsonReadModelBinder(type);
        }
    }
bubuko.com,布布扣

3、其中JsonReadModelBinder实现IModelBinder接口

bubuko.com,布布扣
public class JsonReadModelBinder : IModelBinder
    {
        private Type type;
        public JsonReadModelBinder(Type type)
        {
            this.type = type;
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var request = controllerContext.HttpContext.Request;
            request.InputStream.Position = 0;
            var objs = new object();
            using (var s = new GZipStream(request.InputStream, CompressionMode.Decompress))
            {
                using (var sReader = new StreamReader(s, Encoding.UTF8))
                {
                    string str = sReader.ReadToEnd();
                    if (type == typeof(PostData))
                    {
                        objs = JsonUnit.Deserialize<PostData>(str);
                    }else if (type == typeof(PostComment))
                    {
                        objs = JsonUnit.Deserialize<PostComment>(str);
                    }//if else 扩展
                    sReader.Close();
} }
return objs; }
bubuko.com,布布扣

 




服务器端接受Json数据的绑定实现,布布扣,bubuko.com

服务器端接受Json数据的绑定实现

原文:http://www.cnblogs.com/Benjamin/p/3612083.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!