简体   繁体   English

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

[英]webapi 2 global exception handling, controller-context is null

In WebAPI 2 global exception handler, I am trying to get the reference of the controller object from where the error is thrown. 在WebAPI 2全局异常处理程序中,我试图从引发错误的位置获取控制器对象的引用。

below is the code for it: 下面是它的代码:

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 and action variables above are coming out to be null. 上面的controlleraction变量为空。

Any pointers why so? 任何指针为何如此?

Assuming that the exception gets thrown from within an action method. 假设从动作方法中引发了异常。

Make sure to return true from the ShouldHandle method of your ExceptionHandler . 确保从ExceptionHandlerShouldHandle方法返回true
Without this, the context.ExceptionContext.ControllerContext in the Handle method will be null. 否则, Handle方法中的context.ExceptionContext.ControllerContext将为null。

For some reason the context.ExceptionContext.ActionContext is always null, but this one can be retrieved from the HttpControllerContext via its Controller property. 由于某种原因, context.ExceptionContext.ActionContext始终为null,但是可以通过HttpControllerContextController属性从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;
    }            
}

If you only care about exception logging, prefer an ExceptionLogger over an ExceptionHandler . 如果您只关心异常日志记录,则最好使用ExceptionLogger而不是ExceptionHandler
See MSDN . 参见MSDN

Exception loggers are the solution to seeing all unhandled exception caught by Web API. 异常记录器是查看Web API捕获的所有未处理异常的解决方案。
Exception loggers always get called, even if we're about to abort the connection. 即使我们要中止连接,也总是会调用异常记录器。
Exception handlers only get called when we're still able to choose which response message to send. 仅当我们仍然能够选择发送哪个响应消息时,才会调用异常处理程序。

Here also, retrieve the HttpActionContext from the HttpControllerContext as shown above. 同样在这里,从HttpControllerContext检索HttpActionContext ,如上所示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM