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

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

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

 

 

2、继承CustomModelBinder类:

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

3、其中JsonReadModelBinder实现IModelBinder接口

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; }

 




服务器端接受Json数据的绑定实现,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。