在WebAPI 2全局异常处理程序中,我试图从抛出错误的地方获取控制器对象的引用。
下面是它的代码:
public class CustomExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
var controller = context.ExceptionContext.ControllerContext;
var action = context.ExceptionContext.ActionContext;
//.....some code after this
}
}上面的controller 和 action 变量都是null.。
有什么建议吗?为什么?
发布于 2018-06-25 07:48:17
假设异常是从操作方法中抛出的。
确保从您的true的ShouldHandle方法返回ExceptionHandler。
没有这一点,Handle方法中的Handle将为null。
由于某些原因,context.ExceptionContext.ActionContext始终是空的,但是可以通过其Controller属性从HttpControllerContext中检索这个值。
class MyExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
HttpControllerContext controllerContext = context.ExceptionContext.ControllerContext;
if (controllerContext != null)
{
System.Web.Http.ApiController apiController = controllerContext.Controller as ApiController;
if (apiController != null)
{
HttpActionContext actionContext = apiController.ActionContext;
// ...
}
}
// ...
base.Handle(context);
}
public override Boolean ShouldHandle(ExceptionHandlerContext context)
{
return true;
}
}如果您只关心异常日志记录,则更喜欢使用ExceptionLogger而不是ExceptionHandler。
见MSDN。
异常记录器是查看Web捕获的所有未处理异常的解决方案。 异常记录器总是会被调用,即使我们要中止连接。 只有当我们仍然能够选择发送哪条响应消息时,才会调用异常处理程序。
这里,也可以从HttpActionContext中检索HttpControllerContext,如上面所示。
https://stackoverflow.com/questions/38945133
复制相似问题