138

在我的一个控制器操作中,我返回一个非常大JsonResult的来填充网格。

我收到以下InvalidOperationException异常:

使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过了 maxJsonLength 属性上设置的值。

maxJsonLength不幸的是,将 中的属性设置web.config为更高的值不会显示任何效果。

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

我不想将它作为这个SO 答案中提到的字符串传回。

在我的研究中,我遇到了这篇博客文章,其中建议编写自己的ActionResult(例如LargeJsonResult : JsonResult)来绕过这种行为。

这是唯一的解决方案吗?
这是 ASP.NET MVC 中的错误吗?
我错过了什么吗?

非常感激任何的帮助。

4

15 回答 15

254

看来这已在 MVC4 中修复。

你可以这样做,这对我很有效:

public ActionResult SomeControllerAction()
{
  var jsonResult = Json(veryLargeCollection, JsonRequestBehavior.AllowGet);
  jsonResult.MaxJsonLength = int.MaxValue;
  return jsonResult;
}
于 2012-12-19T20:57:11.570 回答
33

您也可以ContentResult按照此处的建议使用,而不是 subclassing JsonResult

var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };

return new ContentResult()
{
    Content = serializer.Serialize(data),
    ContentType = "application/json",
};
于 2012-03-29T18:47:11.773 回答
27

不幸的是,默认 JsonResult 实现忽略了 web.config 设置。所以我想你需要实现一个自定义的 json 结果来克服这个问题。

于 2011-04-17T13:56:28.270 回答
23

不需要自定义类。这就是所有需要的:

return new JsonResult { Data = Result, MaxJsonLength = Int32.MaxValue };

Result您希望序列化的数据 在哪里。

于 2013-04-08T01:57:10.020 回答
8

我很惊讶没有人建议使用结果过滤器。这是全局挂钩到操作/结果管道的最干净的方法:

public class JsonResultFilter : IResultFilter
{
    public int? MaxJsonLength { get; set; }

    public int? RecursionLimit { get; set; }

    public void OnResultExecuting(ResultExecutingContext filterContext)
    {
        if (filterContext.Result is JsonResult jsonResult)
        {
            // override properties only if they're not set
            jsonResult.MaxJsonLength = jsonResult.MaxJsonLength ?? MaxJsonLength;
            jsonResult.RecursionLimit = jsonResult.RecursionLimit ?? RecursionLimit;
        }
    }

    public void OnResultExecuted(ResultExecutedContext filterContext)
    {
    }
}

然后,使用以下方法注册该类的实例GlobalFilters.Filters

GlobalFilters.Filters.Add(new JsonResultFilter { MaxJsonLength = int.MaxValue });
于 2020-02-07T22:03:29.917 回答
6

如果使用Json.NET生成json字符串,则不需要设置MaxJsonLength值。

return new ContentResult()
{
    Content = Newtonsoft.Json.JsonConvert.SerializeObject(data),
    ContentType = "application/json",
};
于 2015-02-06T06:29:52.327 回答
6

替代 ASP.NET MVC 5 修复:

就我而言,错误是在请求期间发生的。在我的场景中,最好的方法是修改将JsonValueProviderFactory修复应用于全局项目的实际值,并且可以通过编辑global.cs文件来完成。

JsonValueProviderConfig.Config(ValueProviderFactories.Factories);

添加一个 web.config 条目:

<add key="aspnet:MaxJsonLength" value="20971520" />

然后创建以下两个类

public class JsonValueProviderConfig
{
    public static void Config(ValueProviderFactoryCollection factories)
    {
        var jsonProviderFactory = factories.OfType<JsonValueProviderFactory>().Single();
        factories.Remove(jsonProviderFactory);
        factories.Add(new CustomJsonValueProviderFactory());
    }
}

这基本上是在中找到的默认实现的精确副本,System.Web.Mvc但添加了可配置的 web.config appsetting 值aspnet:MaxJsonLength

public class CustomJsonValueProviderFactory : ValueProviderFactory
{

    /// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
    /// <returns>A JSON value-provider object for the specified controller context.</returns>
    /// <param name="controllerContext">The controller context.</param>
    public override IValueProvider GetValueProvider(ControllerContext controllerContext)
    {
        if (controllerContext == null)
            throw new ArgumentNullException("controllerContext");

        object deserializedObject = CustomJsonValueProviderFactory.GetDeserializedObject(controllerContext);
        if (deserializedObject == null)
            return null;

        Dictionary<string, object> strs = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
        CustomJsonValueProviderFactory.AddToBackingStore(new CustomJsonValueProviderFactory.EntryLimitedDictionary(strs), string.Empty, deserializedObject);

        return new DictionaryValueProvider<object>(strs, CultureInfo.CurrentCulture);
    }

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

        string fullStreamString = (new StreamReader(controllerContext.HttpContext.Request.InputStream)).ReadToEnd();
        if (string.IsNullOrEmpty(fullStreamString))
            return null;

        var serializer = new JavaScriptSerializer()
        {
            MaxJsonLength = CustomJsonValueProviderFactory.GetMaxJsonLength()
        };
        return serializer.DeserializeObject(fullStreamString);
    }

    private static void AddToBackingStore(EntryLimitedDictionary backingStore, string prefix, object value)
    {
        IDictionary<string, object> strs = value as IDictionary<string, object>;
        if (strs != null)
        {
            foreach (KeyValuePair<string, object> keyValuePair in strs)
                CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);

            return;
        }

        IList lists = value as IList;
        if (lists == null)
        {
            backingStore.Add(prefix, value);
            return;
        }

        for (int i = 0; i < lists.Count; i++)
        {
            CustomJsonValueProviderFactory.AddToBackingStore(backingStore, CustomJsonValueProviderFactory.MakeArrayKey(prefix, i), lists[i]);
        }
    }

    private class EntryLimitedDictionary
    {
        private static int _maximumDepth;

        private readonly IDictionary<string, object> _innerDictionary;

        private int _itemCount;

        static EntryLimitedDictionary()
        {
            _maximumDepth = CustomJsonValueProviderFactory.GetMaximumDepth();
        }

        public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
        {
            this._innerDictionary = innerDictionary;
        }

        public void Add(string key, object value)
        {
            int num = this._itemCount + 1;
            this._itemCount = num;
            if (num > _maximumDepth)
            {
                throw new InvalidOperationException("The length of the string exceeds the value set on the maxJsonLength property.");
            }
            this._innerDictionary.Add(key, value);
        }
    }

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

    private static string MakePropertyKey(string prefix, string propertyName)
    {
        if (string.IsNullOrEmpty(prefix))
        {
            return propertyName;
        }
        return string.Concat(prefix, ".", propertyName);
    }

    private static int GetMaximumDepth()
    {
        int num;
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        if (appSettings != null)
        {
            string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
            if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
            {
                return num;
            }
        }
        return 1000;
    }

    private static int GetMaxJsonLength()
    {
        int num;
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        if (appSettings != null)
        {
            string[] values = appSettings.GetValues("aspnet:MaxJsonLength");
            if (values != null && values.Length != 0 && int.TryParse(values[0], out num))
            {
                return num;
            }
        }
        return 1000;
    }
}
于 2018-06-03T11:03:07.117 回答
4

还有一点其他情况 - 数据从客户端发送到服务器。当您使用控制器方法并且模型很大时:

    [HttpPost]
    public ActionResult AddOrUpdateConsumerFile(FileMetaDataModelView inputModel)
    {
        if (inputModel == null) return null;
     ....
    }

系统抛出类似这样的异常“使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串的长度超过 maxJsonLength 属性上设置的值。参数名称:输入”

在这种情况下,仅更改 Web.config 设置不足以提供帮助。您还可以覆盖 mvc json 序列化程序以支持巨大的数据模型大小或从请求中手动反序列化模型。您的控制器方法变为:

   [HttpPost]
    public ActionResult AddOrUpdateConsumerFile()
    {
        FileMetaDataModelView inputModel = RequestManager.GetModelFromJsonRequest<FileMetaDataModelView>(HttpContext.Request);
        if (inputModel == null) return null;
        ......
    }

   public static T GetModelFromJsonRequest<T>(HttpRequestBase request)
    {
        string result = "";
        using (Stream req = request.InputStream)
        {
            req.Seek(0, System.IO.SeekOrigin.Begin);
            result = new StreamReader(req).ReadToEnd();
        }
        return JsonConvert.DeserializeObject<T>(result);
    }
于 2019-03-27T15:06:02.850 回答
4

我通过点击这个 链接解决了这个问题

namespace System.Web.Mvc
{
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);
    }
}

}

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        //Remove and JsonValueProviderFactory and add JsonDotNetValueProviderFactory
        ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType<JsonValueProviderFactory>().FirstOrDefault());
        ValueProviderFactories.Factories.Add(new JsonDotNetValueProviderFactory());
    }
于 2016-06-15T23:31:16.917 回答
2

您可以尝试在您的 LINQ 表达式中仅定义您需要的字段。

例子。想象一下,您有一个带有 ID、名称、电话和图片(字节数组)的模型,需要从 json 加载到选择列表中。

LINQ 查询:

var listItems = (from u in Users where u.name.Contains(term) select u).ToList();

这里的问题是获取所有字段的“ select u ”。所以,如果你有大照片,booomm。

怎么解决?非常非常简单。

var listItems = (from u in Users where u.name.Contains(term) select new {u.Id, u.Name}).ToList();

最佳做法是仅选择您将使用的字段。

记住。这是一个简单的提示,但可以帮助许多 ASP.NET MVC 开发人员。

于 2014-09-24T01:18:25.857 回答
2
    protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
    {
        return new JsonResult()
        {
            Data = data,
            ContentType = contentType,
            ContentEncoding = contentEncoding,
            JsonRequestBehavior = behavior,
            MaxJsonLength = Int32.MaxValue
        };
    }

是我在 MVC 4 中的修复。

于 2018-10-16T22:58:01.867 回答
1

在我将 Action 更改为[HttpPost]. 并将 ajax 类型设为POST.

    [HttpPost]
    public JsonResult GetSelectedSignalData(string signal1,...)
    {
         JsonResult result = new JsonResult();
         var signalData = GetTheData();
         try
         {
              var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };

            result.Data = serializer.Serialize(signalData);
            return Json(result, JsonRequestBehavior.AllowGet);
            ..
            ..
            ...

    }

ajax 调用为

$.ajax({
    type: "POST",
    url: some_url,
    data: JSON.stringify({  signal1: signal1,.. }),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        if (data !== null) {
            setValue();
        }

    },
    failure: function (data) {
        $('#errMessage').text("Error...");
    },
    error: function (data) {
        $('#errMessage').text("Error...");
    }
});
于 2018-07-04T12:08:50.863 回答
0

在代码返回 JsonResult 对象之前,您需要手动读取配置部分。只需从 web.config 单行读取:

        var jsonResult = Json(resultsForAjaxUI);
        jsonResult.MaxJsonLength = (ConfigurationManager.GetSection("system.web.extensions/scripting/webServices/jsonSerialization") as System.Web.Configuration.ScriptingJsonSerializationSection).MaxJsonLength;
        return jsonResult;

确保您在 web.config 中定义了配置元素

于 2017-08-15T11:28:06.007 回答
0

这对我有用

        JsonSerializerSettings json = new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        };
        var result = JsonConvert.SerializeObject(list, Formatting.Indented, json);
        return new JsonResult { Data = result, MaxJsonLength = int.MaxValue };
于 2018-08-21T14:38:58.283 回答
0

如果您从控制器返回视图并且想要在 cshtml 中以 json 编码时增加视图包数据的长度,则可以将此代码放在 cshtml 中

@{
    var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
    jss.MaxJsonLength = Int32.MaxValue;
    var userInfoJson = jss.Serialize(ViewBag.ActionObj);
}

var dataJsonOnActionGrid1 = @Html.Raw(userInfoJson);

现在,dataJsonOnActionGrid1 将可以在 js 页面上访问,您将获得正确的结果。

谢谢

于 2019-04-01T07:52:11.313 回答