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
上面的变量都是空的.
任何指针为什么这样?
假设异常是从操作方法中抛出的。
确保true
从ShouldHandle
您的ExceptionHandler
.
没有这一点,将context.ExceptionContext.ControllerContext
在Handle
法会是空的。
出于某种原因,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
如上所示。