解决ASP.NET MVC(post数据)Json请求太大,无法反序列化(The JSON request was too large to be deserialized)

时间:2022-05-28 00:02:09

这个问题出现的场景并不是很多,当你向服务端异步(ajax)post数据非常大的情况下(比如做权限管理的时候给某个角色分配权限那么就可能会出现,我所遇到的就是该角色大概200个模块每个模块平均2个功能----那么发送到服务端action的将是一个有着400个对象的数组)

之前我们向服务端异步post数组可能需要使用

 $.ajax({
type: 'POST',
url: '/system/SaveRoleReModule',
dataType: "json",
contentType: "application/json;charset=utf-8",
data: JSON.stringify({ tree: treearr, roleId: roleid }),
success: function (d) {
if (d > 0) {
$.popAlter({ content: '操作成功!', hideOkBtn:true,btnTxt:'确定'});
// kq_show_info('系统提示', '操作成功', 2000);
}
},
error: function (e) {
//kq_show_info('系统提示', e.responseText, 2000);
}
});

但是当我们把javascriptserializer换成json.net之后以上方式将可以简化为以下写法:

 $.ajax({
type:'post',
url:'',
data:{o:arr}
success:function(d){},
error:function(e){}
})

解决方法:

方案1.asp.net mvc默认的json序列化ValueProviderFactory使用的是javascriptserializer,可以在配置文件web.config中设置:

<add key="aspnet:MaxJsonDeserializerMembers" value="150000000" />

<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644"/>
</webServices>
</scripting>
</system.web.extensions>

方案2:重写默认的ValueProviderFactory,继承ValueProviderFactory抽象类使用json.net替换javascriptserializer,并且在application_start时将默认的ValueProviderFactory移除,使用自定义的ValueProviderFactory

 public sealed class JsonDotNetValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext"); if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
return null; var reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
var bodyText = reader.ReadToEnd(); return String.IsNullOrEmpty(bodyText) ? null : new DictionaryValueProvider<object>(JsonConvert.DeserializeObject<ExpandoObject>(bodyText, new ExpandoObjectConverter()) , CultureInfo.CurrentCulture);
}
}

global.asax

 protected void Application_Start()
{
log4net.Config.XmlConfigurator.Configure();
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory());
//AutofacBuilder<ModulesRepository>.RegisterPersistent();
}

网上介绍最多的是第一种方案,但是我觉得json.net比默认的javascriptserializer性能要好所以采用第二种方案!