在使用mvc4进行ajax提交大量数据时,系统会抛出System.ArgumentException异常。

10

我正在使用ajax post方法将来自JavaScript的数据发布到mvc4,但是它失败并出现以下异常

string exceeds the value set on the maxJsonLength property.
Parameter name: input
System.ArgumentException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property. 

我已经尝试在web config中设置配置,但没有起作用。

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

我还尝试了下面的链接,但都没有起作用: http://forums.asp.net/t/1751116.aspx?How+to+increase+maxJsonLength+for+JSON+POST+in+MVC3
var editorText = eval(htmlEditor).GetHtml();     
$.ajax({type: 'POST',
    cache: false,
    contentType: 'application/json; charset=utf-8',
    url: "../Home/SaveExceptionLetter",
    data: JSON.stringify({ message: editorText }),
    datatype: 'json',
    success: function () {
    });
} });

[HttpPost]
[ValidateInput(false)]
public void SaveExceptionLetter(string message){
    //processing this message
}

string exceeds the value set on the maxJsonLength property.
Parameter name: input
System.ArgumentException: Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
Parameter name: input
   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
   at System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext)
   at System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext)
   at System.Web.Mvc.ValueProviderFactoryCollection.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory)
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
   at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
   at System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext)
   at System.Web.Mvc.ControllerBase.get_ValueProvider()
   at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
   at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState)

我应用的Web配置设置是 <system.web.extensions> <scripting> <webServices> <jsonSerialization maxJsonLength="2147483647"/> </webServices> </scripting> </system.web.extensions> - usFarswan
请查看以下链接: https://dev59.com/c3M_5IYBdhLWcg3w9oQA?rq=1 - Anshul Nigam
2个回答

21

嗨@usFarswan,这正是我半小时前遇到的问题,解决方案在http://forums.asp.net/t/1751116.aspx?How+to+increase+maxJsonLength+for+JSON+POST+in+MVC3

你可以像这样实现,在global.asax中添加以下行,指向///*****。

namespace MyWebApp
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();


            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            XmlConfigurator.Configure();
            DbHelper.getSessionFactory();

            ///// **********
             JsonValueProviderFactory jsonValueProviderFactory = null;

            foreach (var factory in ValueProviderFactories.Factories)
            {
                if (factory is JsonValueProviderFactory)
                {
                    jsonValueProviderFactory = factory as JsonValueProviderFactory;
                }
            }

            //remove the default JsonVAlueProviderFactory
            if (jsonValueProviderFactory != null) ValueProviderFactories.Factories.Remove(jsonValueProviderFactory);

            //add the custom one
            ValueProviderFactories.Factories.Add(new CustomJsonValueProviderFactory());**
       /////*************
        }
    }




     ///********
    public sealed class CustomJsonValueProviderFactory : ValueProviderFactory
    {

        private static void AddToBackingStore(Dictionary<string, object> backingStore, string prefix, object value)
        {
            IDictionary<string, object> d = value as IDictionary<string, object>;
            if (d != null)
            {
                foreach (KeyValuePair<string, object> entry in d)
                {
                    AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
                }
                return;
            }

            IList l = value as IList;
            if (l != null)
            {
                for (int i = 0; i < l.Count; i++)
                {
                    AddToBackingStore(backingStore, MakeArrayKey(prefix, i), l[i]);
                }
                return;
            }

            // primitive
            backingStore[prefix] = value;
        }

        private static object GetDeserializedObject(ControllerContext controllerContext)
        {
            if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            {
                // not JSON request
                return null;
            }

            StreamReader reader = new StreamReader(controllerContext.HttpContext.Request.InputStream);
            string bodyText = reader.ReadToEnd();
            if (String.IsNullOrEmpty(bodyText))
            {
                // no JSON data
                return null;
            }

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            serializer.MaxJsonLength = int.MaxValue; //increase MaxJsonLength.  This could be read in from the web.config if you prefer
            object jsonData = serializer.DeserializeObject(bodyText);
            return jsonData;
        }

        public override IValueProvider GetValueProvider(ControllerContext controllerContext)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            object jsonData = GetDeserializedObject(controllerContext);
            if (jsonData == null)
            {
                return null;
            }

            Dictionary<string, object> backingStore = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            AddToBackingStore(backingStore, String.Empty, jsonData);
            return new DictionaryValueProvider<object>(backingStore, CultureInfo.CurrentCulture);
        }

        private static string MakeArrayKey(string prefix, int index)
        {
            return prefix + "[" + index.ToString(CultureInfo.InvariantCulture) + "]";
        }

        private static string MakePropertyKey(string prefix, string propertyName)
        {
            return (String.IsNullOrEmpty(prefix)) ? propertyName : prefix + "." + propertyName;
        }
    }
   ///*************
} 

2
这是网络上唯一对我有效的解决方案。谢谢! :) 这里有一个更短的代码来替换值提供程序工厂:https://dev59.com/UmUq5IYBdhLWcg3wVu6D#14591946 +1 - user2173353
非常好的解决方案,谢谢! - Ahmed Mostafa
运行得非常好! - Jordan
这是真正的解决方案。感谢 @katmanco。 - Tagi
非常感谢,这个方法对我有用,而不是其他的web.config解决方案。再次感谢。你救了我。这个错误让我疯狂,浪费了我很多时间。 - Sagar

0

在 web.config 中还有另一个设置,您可以尝试增加:

<system.web>
  // the default request size is 4096 KB (4 MB) this will increase it to 100 MB
  <httpRuntime targetFramework="4.5" maxRequestLength="102400" /> 
<system.web> 

我已经设置了请求长度,但它没有起作用。 - usFarswan
我已经编辑了现有的问题,请在上面找到详细信息。 - usFarswan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接