Reputation: 131
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?
Upvotes: 10
Views: 1708
Reputation: 23214
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.
Upvotes: 8