使用MVC之后, 默认的ActionResult 有很多子类譬如 JsonResult之类, 可以很方便. 基本用法如下:
public ActionResult GetVacation() { var dt = ...(省略); if (dt == null || dt.Rows.Count==0) return Json(new { success = false, msg = "相应空逻辑!" }); ; return Json(new { success = true, ...(省略) });//省略内容 }
默认只能采用POST方式调用方法, Get 不行, 需要构建 JsonRequestBehavior 为AllowGet 方式. 返回 response.
public JsonResult W1ArchiveOTUpdate(string xxx1, string xxx2) { JsonResult response = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet }; var ret = Biz.XXX(Request.Cookies["XXX"].Value); response.Data = new { success = ret.Success, msg = ret.Msg }; return response; }
另一种情况, 返回数据行过多, 数据超过了默认限定, 记不清多少了, 所以采用了一个JsonResult 子类来定义到int.MAX. 如果还不行, 请考虑业务问题, 能分页就分页把.
过度方案:
public class LargeJsonResult : JsonResult { const string JsonRequest_GetNotAllowed = "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."; public LargeJsonResult() { MaxJsonLength = int.MaxValue;//102400; RecursionLimit = 100; } public new int MaxJsonLength { get; set; } public new int RecursionLimit { get; set; } 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(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) { JavaScriptSerializer serializer = new JavaScriptSerializer() { MaxJsonLength = MaxJsonLength, RecursionLimit = RecursionLimit }; response.Write(serializer.Serialize(Data)); } } } //调用方式 public ActionResult XXXX(string XXX1, string XXX2) { var ret = Biz.XXX(); return new LargeJsonResult { Data = ret.Data }; //return Json(ret); }
参考: