【问题标题】:try catch does not work for "return Json()" exceptionstry catch 不适用于“return Json()”异常
【发布时间】: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


【解决方案1】:

我无法重现该错误,但无论如何,Json 方法实现已经在内部捕获异常并将其转换为完整的 HTTP 5xx 响应。 return Json() 调用也不例外。

你没有机会捕捉到异常,因为......你会怎么做?生成 HTTP 5xx 响应? MVC 框架已经为您完成了这项工作。

【讨论】:

  • 什么是“成熟的 HTTP”?
  • 这是“成熟的 HTTP 5xx 响应”。我想说的是整个 HTTP 响应,没有什么可添加的。这就是为什么您只返回由 Json 方法生成的 ActionResult 的原因 - 该方法旨在构建整个 HTTP 响应,包括错误响应。
【解决方案2】:

试试这样:

ActionResult result;
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.
            result= Json(result, JsonRequestBehavior.AllowGet);
        }
        catch
        {
            //when exception is raised the catch will not be called
        }
return result;

【讨论】:

  • 我要返回JsonResult。
  • 这与 OP 具​​有 相同 的行为。 (假设您也像 OP 一样返回 catch,否则代码无法编译。)
  • @Servy OP 代表什么?
猜你喜欢
  • 2012-05-14
  • 2015-06-21
  • 2011-05-27
  • 1970-01-01
  • 2017-08-07
  • 2017-09-22
  • 1970-01-01
  • 2011-09-16
  • 1970-01-01
相关资源
最近更新 更多