我已经将Newton Soft添加到组合中,并将此博客用作模板:http://wingkaiwan.com/2012/12/28/replacing-mvc-javascriptserializer-with-json-net-jsonserializer/
我现在有:
public class BaseJsonController : BaseController
{
protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonNetResult
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior
};
}
}
public class JsonNetResult : JsonResult
{
public JsonNetResult()
{
Settings = new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Error
};
}
public JsonSerializerSettings Settings { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException("JSON GET is not allowed");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (this.Data == null)
return;
var scriptSerializer = JsonSerializer.Create(this.Settings);
using (var sw = new StringWriter())
{
scriptSerializer.Serialize(sw, this.Data);
response.Write(sw.ToString());
}
}
}
现在,在我的控制器中,我这样做了:
[HandleError]
public class ProcurementActionsController : BaseJsonController
{
...
[GridAction]
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult AjaxGetAll(string pageFilter = null, string searchTerm = null)
{
var rawData = GetProcurementActions(pageFilter);
return new JsonNetResult
{
Data = new GridModel { Data = rawData },
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Settings = { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }
};
}
...
}
然而,我仍然得到同样的错误!根据堆栈跟踪,它仍在尝试使用JavaScriptSerializer而不是JsonSerializer:
[InvalidOperationException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.]
System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat) +188
System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj) +56
System.Web.Mvc.JsonResult.ExecuteResult(ControllerContext context) +418
System.Web.Mvc.<>c__DisplayClass14.<InvokeActionResultWithFilters>b__11() +31
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +656883
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +656883
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +254
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +658100
System.Web.Mvc.Controller.ExecuteCore() +125
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +48
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +15
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +85
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +51
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +454
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +263
是因为异步调用吗?如果是,我需要在BaseJsonController中重写什么才能调用正确的ExecuteResult(…)方法?
在MVC 4和5中,这应该可以通过web配置文件中的参数轻松修复。
我在MVC3中也遇到了同样的问题,只是通过替换app_start中的ValueProviderFactories来修复它,如下所示:
http://forums.asp.net/t/1751116.aspx
[GridAction]
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult AjaxGetAll(string pageFilter = null, string searchTerm = null)
{
var rawData = GetProcurementActions(pageFilter);
var gridData = new GridModel { Data = rawData };
var json = JsonConvert.SerializeObject(gridData).Replace(""Total":0,"Aggregates":null", String.Format(""Total":{0},"Aggregates":null", rawData.Count));
return new ContentResult { Content = json, ContentType = "application/json" };
}
- 从数据库中获取数据
- 需要将ViewModel(List)转换为Telerik的GridModel对象
- 使用Newton Soft的JsonSerializer将GridModel转换为JSON字符串(此处没有长度限制!)Telerik Grid需要知道总记录,但由于某些原因,它不在JSON中。通过Replace()方法更新它
- 请使用ContentResult对象,而不是ActionResult或JsonResult。有了这个,您可以定义自己的数据负载
这个精确解决方案的唯一缺点是如果它最终达到4GB左右。在这一点上,它可能会崩溃大多数浏览器,除非你有办法大块返回。我会添加一个最大长度的检查,然后抛出一个错误。