在尝试返回 JsonResult 时更改 web 配置中的默认 maxJsonLength 将不起作用,因为 asp.net 将尝试在内部序列化您的对象,同时完全忽略您设置的 maxJsonLenght。
解决此问题的一种简单方法是在您的方法中返回 string 而不是 JsonResult,并使用您的自定义 maxJsonLenght 实例化一个新的 JavaScriptSerializer,如下所示:
[HttpPost]
public string MyAjaxMethod()
{
var veryBigJson = new object();
JavaScriptSerializer s = new JavaScriptSerializer
{
MaxJsonLength = int.MaxValue
};
return s.Serialize(veryBigJson);
}
然后在您看来,您只需使用 JSON.parse(data) 将其解析回 json
另一种方法是在您可以实际控制 maxJsonLenght 时创建自己的 JsonResult 类,如下所示:
public class LargeJsonResult : JsonResult
{
const string JsonRequest_GetNotAllowed = "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.";
public LargeJsonResult(object data,JsonRequestBehavior jsonRequestBehavior=JsonRequestBehavior.DenyGet,int maxJsonLength=Int32.MaxValue)
{
Data = data;
JsonRequestBehavior = jsonRequestBehavior;
MaxJsonLength = maxJsonLength;
RecursionLimit = 100;
}
public new int MaxJsonLength { get; set; }
public new int RecursionLimit { get; set; }
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(JsonRequest_GetNotAllowed);
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer() { MaxJsonLength = MaxJsonLength, RecursionLimit = RecursionLimit };
response.Write(serializer.Serialize(Data));
}
}
}
在您的方法上,您只需更改类型并返回该类的新实例
[HttpPost]
public LargeJsonResult MyAjaxMethod()
{
var veryBigJson = new object();
return new LargeJsonResult(veryBigJson);
}
来源:https://brianreiter.org/2011/01/03/custom-jsonresult-class-for-asp-net-mvc-to-avoid-maxjsonlength-exceeded-exception/