最好的选择是从JsonResult类继承并覆盖Execute方法,例如
public class CustomJsonResult: JsonResult{ public CustomJsonResult() { JsonRequestBehavior = JsonRequestBehavior.DenyGet; } public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed); } HttpResponsebase response = context.HttpContext.Response; if (!String.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { CustomJsSerializer serializer = new CustomJsSerializer(); response.Write(serializer.Serialize(Data)); } }}代码来自mvc3的JsonResult类,并更改了此行
JavascriptSerializer serializer = new JavascriptSerializer();
至
CustomJsSerializer serializer = new CustomJsSerializer();
您可以在操作方法中使用此类,例如
public JsonResult result(){ var model = GetModel(); return new CustomJsonResult{Data = model};}另外,您可以在base控制器中覆盖Controller类的json方法,例如
public class baseController:Controller{ protected internal override JsonResult Json(object data) { return new CustomJsonResult { Data = data }; }}现在,如果您拥有baseController中的所有控制器,
returnJson(data)则将调用序列化方案。
Json您还可以选择重写方法的其他重载。



