我有带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?
答案 0 :(得分: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;
}
}
PS。新年快乐! :)