如果发生异常,则返回特殊的JsonResult

时间:2011-02-06 21:15:18

标签: asp.net-mvc exception-handling

public JsonResult Menu() { // Exception }

我需要应用程序不将用户重定向到404页面,但返回特殊的JSON结果,如{“result”:1}。
我想知道,有没有其他解决方案,而不是尝试捕捉。

1 个答案:

答案 0 :(得分:6)

您可以实施与FilterAttribute类似的自己的HandleErrorAttribute

HandleErrorAttribute通常在发生错误时执行重定向,但您可以实现返回JsonResult的类似属性。如下所示:

public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        if (filterContext == null)
        {
            throw new ArgumentNullException("filterContext");
        }

        filterContext.Result = new JsonResult
        {
            Data = new { result = 1 },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
        filterContext.ExceptionHandled = true;
    }
}

然后

[CustomHandleError]
public JsonResult Menu()
{
    throw new Exception();
}

我建议您download the MVC source code from CodePlex并检查HandleErrorAttribute的当前实施情况。它比我上面的粗略实现更加微妙,你可能想要它的一些功能。

相关问题