不幸的是,Eric Leschinski 的评论中提供的链接仅显示了如何实现System.Web.Mvc.IExceptionFilter接口,而不是System.Web.Http.Filters.IExceptionFilter接口。第一个用于常规 MVC 控制器,而第二个针对ApiCorollers。
这是我想出的一个简单的类示例,用于记录我的 ApiControllers 中抛出的未处理异常:
public class ExceptionLoggerFilter: IExceptionFilter
{
public ExceptionLoggerFilter(Logger logger)
{
this.logger = logger;
}
public bool AllowMultiple { get { return true; } }
public Task ExecuteExceptionFilterAsync(
HttpActionExecutedContext actionExecutedContext,
CancellationToken cancellationToken)
{
return Task.Factory.StartNew(() =>
{
logger.Error("web service error", actionExecutedContext.Exception);
}, cancellationToken);
}
private Logger logger;
}
启用此过滤器所需要做的就是在您的 Global.asax Application_Start 方法中注册它:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// allocate filter and add it to global configuration
var exceptionLogger = new ExceptionLoggerFilter(Container.Get<Logger>());
GlobalConfiguration.Configuration.Filters.Add(exceptionLogger);
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
我希望这可以帮助其他谷歌员工!