webapi 2全局异常处理,controller-context为null

sh0*_*007 6 c# error-handling asp.net-web-api2

在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
     }
}
Run Code Online (Sandbox Code Playgroud)

controller以及action上面的变量都是空的.

任何指针为什么这样?

pfx*_*pfx 6

假设异常是从操作方法中抛出的。

确保trueShouldHandle您的ExceptionHandler.
没有这一点,将context.ExceptionContext.ControllerContextHandle法会是空的。

出于某种原因,context.ExceptionContext.ActionContext始终为空,但可以HttpControllerContext通过其Controller属性从 中检索此值。

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;
    }            
}
Run Code Online (Sandbox Code Playgroud)

如果你只关心异常记录,更喜欢ExceptionLogger过的ExceptionHandler
请参阅MSDN

异常记录器是查看 Web API 捕获的所有未处理异常的解决方案。
异常记录器总是被调用,即使我们要中止连接。
只有当我们仍然能够选择要发送的响应消息时,才会调用异常处理程序。

在这里,也可以HttpActionContext从 中检索,HttpControllerContext如上所示。