MVC 3 json请求应该在异常时接收json响应

Das*_*shu 3 error-handling asp.net-mvc-3

我正在寻找一个好的/智能/干净的方式来全局处理错误,这样如果请求是Json并且发生异常,结果应该是json而不是html.

寻找现有的解决方案或如何建立自己的一些信息.

Dar*_*rov 7

一种常见的方法是编写自定义异常过滤器:

public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
{
    public void OnException(ExceptionContext filterContext)
    {
        filterContext.ExceptionHandled = true;
        filterContext.Result = new JsonResult
        {
            Data = new { success = false, error = filterContext.Exception.ToString() },
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

可以在Global.asax中注册为全局过滤器.然后简单地查询一些动作:

$.getJSON('/someController/someAction', function (result) {
    if (!result.success) {
        alert(result.error);
    } else {
        // handle the success
    }
});
Run Code Online (Sandbox Code Playgroud)