OnException - 两次调用

LIN*_*dka 3 .net asp.net-mvc

我有带OnException处理程序的BaseController类.

public class ApiBaseController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        filterContext.Result = ...
        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        filterContext.ExceptionHandled = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

我继承的控制器在其操作上有自定义的HandleJsonError:

public class ApiCompanyController : ApiBaseController
{
    [HttpPost, HandleJsonError]
    public ActionResult Delete(int id)
    {
        // ...
        if (...) throw new DependentEntitiesExistException(dependentEntities);
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

HandleJsonError是:

public class HandleJsonError : HandleErrorAttribute
{
    public override void OnException(ExceptionContext exceptionContext)
    {
        // ...
        exceptionContext.ExceptionHandled = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

当DependentEntitiesExistException异常上升时,将调用基本控制器和HandleJsonError的OnException处理程序.在HandleJsonError的OnException完成后,如何才能调用基本控制器OnException?

Dan*_*.G. 5

如果已经处理了异常,请检查您的基本控制器.如果是,请跳过方法执行:

public class ApiBaseController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        //Do not continue if exception already handled
        if (filterContext.ExceptionHandled) return;

        //Error handling logic
        filterContext.Result = ...
        filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
        filterContext.ExceptionHandled = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

PS.新年快乐!:)