C# 如何在Web API项目中记录依赖项解析期间引发的异常?

C# 如何在Web API项目中记录依赖项解析期间引发的异常?,c#,asp.net-web-api,autofac,C#,Asp.net Web Api,Autofac,如果控制器的依赖项解析失败,如何设置托管在IIS中的Web API 2(版本5)项目以记录错误?我正在为DI使用Autofac Web API 2集成(3.1版) 在我的Global.asax.cs中,我有以下内容: public class Global : HttpApplication { protected void Application_Start() { var resolver = new AutofacWebApiDependencyResolver(_

如果控制器的依赖项解析失败,如何设置托管在IIS中的Web API 2(版本5)项目以记录错误?我正在为DI使用Autofac Web API 2集成(3.1版)

在我的Global.asax.cs中,我有以下内容:

public class Global : HttpApplication {
    protected void Application_Start() {
        var resolver = new AutofacWebApiDependencyResolver(_container);
        GlobalConfiguration.Configuration.DependencyResolver = resolver;

        // other initialization

        GlobalConfiguration.Configuration.EnsureInitialized(); 

    }

    protected void Application_Error(Object sender, EventArgs e){
        Exception exception = Server.GetLastError();
        if (exception != null) {
            _log.Error("Application error", exception);
        }
    }
}
在类似的MVC项目中,使用
Autofac DependencyResolver
这足以记录当Autofac在创建控制器时无法解析依赖项时引发的
Autofac.Core.DependencyResolutionException
,但在我的Web API项目中,这似乎不起作用,要么没有引发异常,要么我没有设置正确的日志处理程序。相反,不会记录任何消息,而是向客户端返回500响应

如果在依赖项解析过程中没有抛出错误(我的模块设置正确),则一切正常,控制器解析并按预期处理请求

我还设置了另外两个异常记录器,它们也不会记录此异常:

  • 处理未处理的异常事件:AppDomain.CurrentDomain.UnhandledException+=CurrentDomain\u UnhandledException(在Global.asax.cs中)
  • 设置从ExceptionFilterAttribute派生的异常日志记录筛选器。这会记录控制器处理请求时引发的异常,但不会记录在依赖项解析期间引发的异常

这可以在Web API 2.1中通过使用新的


这对我不起作用,它不符合log方法。@你必须这样做。
public class Log4NetExceptionLogger : ExceptionLogger {
    private static readonly ILog _log = LogManager.GetLogger("{your logger name here}");
    public override void Log(ExceptionLoggerContext context) {
        if (context == null) {
            throw new ArgumentNullException("context");
        }
        // When the framework calls an exception logger or an exception handler, it will always provide an Exception and a Request.
        // http://aspnetwebstack.codeplex.com/wikipage?title=Global%20Error%20Handling&referringTitle=Specs
        if (context.Exception == null) {
            throw new ArgumentException("context.Exception is null", "context");
        }
        if (context.Request == null) {
            throw new ArgumentException("context.Request is null", "context");
        }

        _log.Error(context.Request, context.Exception);
    }
}

// In GlobalConfiguration setup in Global.asax.cs
config.Services.Add(typeof(IExceptionLogger), new Log4NetExceptionLogger());