【发布时间】:2016-12-05 13:23:08
【问题描述】:
当json结果中的字符长度很大时,会引发以下异常:
使用 JSON JavaScriptSerializer 进行序列化或反序列化时出错。字符串长度超过 maxJsonLength 属性设置的值。
上述异常是服务器端异常,响应码为 500,所以如果我们将源代码放在 try catch 块中,错误应该在 catch 块中捕获,但 try catch 不适用于这种情况。
您可以通过以下代码测试此问题,请在 asp.net mvc 控制器中使用它:
public JsonResult Test()
{
try
{
var result = "";
var v1 = new JavaScriptSerializer();
for (int i = 0; i < (v1.MaxJsonLength / 100) + 10; i++)
{
result += "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
}
//exception message:
//Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
return Json(result, JsonRequestBehavior.AllowGet);
}
catch
{
//when exception is raised the catch will not be called
return null;
}
}
【问题讨论】:
-
我猜响应头在异常发生时已经写好了。
-
@AntP 这是一个服务器端异常,因此应该触发 catch 块,但在出错后没有触发它。
-
Ali Reza - 是的,我明白了这个问题。
-
Catch 块未触发,因为没有 C# 异常。我运行了您的代码,它在执行“return Json(result, JsonRequestBehavior.AllowGet);”行上的 Action 方法近 3 分钟后到达断点。以及存储在“结果”中的大量数据。
标签: c# asp.net-mvc