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(str); }else if (type == typeof(PostComment)) { objs = JsonUnit.Deserialize (str); }//if else 扩展 sReader.Close(); } } return objs; }