1. 程式人生 > >解決ASP.NET 請求資料太大500錯誤 JSON無法反序列化

解決ASP.NET 請求資料太大500錯誤 JSON無法反序列化

當向服務端提交請求時(ajax)post資料非常大的情況下,post資料中有超過450個物件的陣列時,請求會返回錯誤資訊:JSON無法反序列化

解決方法:

方案一:可以在配置檔案web.config中設定

<appSettings>
  <add key="aspnet:MaxJsonDeserializerMembers" value="10000000"/>
</appSettings>
<configuration>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="2147483644"></jsonSerialization>
      </webServices>
    </scripting>
  </system.web.extensions>
</configuration>

方案二:重寫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()
        {
            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());
        }