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

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


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

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


HandleJsonError是:

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


引发DependentEntitiesExistException异常时,将同时调用基本控制器和HandleJsonError的OnException处理程序。 HandleJsonError的OnException完成后,如何不调用基本控制器OnException?

最佳答案

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

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;
    }
}


PS。新年快乐! :)

10-02 22:20