简体   繁体   中英

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.

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.

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 .
Without this, the context.ExceptionContext.ControllerContext in the Handle method will be null.

For some reason the context.ExceptionContext.ActionContext is always null, but this one can be retrieved from the HttpControllerContext via its Controller property.

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 .
See MSDN .

Exception loggers are the solution to seeing all unhandled exception caught by 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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