我如何成立的WebAPI一个全球性的错误处理程序? [英] How do I set up a global error handler in WebApi?
问题描述
我建立一个.NET的WebAPI应用程序,我想建立一个全球性的错误处理程序(基本上,当一个例外,从任何地方应用冒泡执行的函数)。 此链接感叹支持这一点,但有几个解决办法提供。不幸的是,我似乎无法找到其中的任何有用的文档。
I am building a .NET WebApi application and I would like to set up a global error handler (basically a function that executes when an exception bubbles up from anywhere in the application). this link laments support for this, but several workarounds are offered. Unfortunately, I can't seem to find useful documentation for any of them.
下面是我的要求:
- 捕获例外行动打击的方法,以及在其他地方(例如控制器分辨率)。
- 先后获得了原始异常对象我的处理过程中。
- 有在错误处理过程中接触到我的(Autofac)IOC容器服务(这是一种强烈的想,但不是必须有)。
- 在MVC不依赖(我用纯的WebAPI)。在IIS上没有依赖是非常可取的。
我如何去设置此功能?
推荐答案
如果您使用此命令通过的NuGet更新到网页API V2.1,可得:
If you update to Web API v2.1, available via Nuget with this command:
Install-Package Microsoft.AspNet.WebApi
您可以通过从Exception继承记录器创建一个全局异常处理。
You can create a Global Exception Handler by inheriting from Exception Logger.
下面是一个例子:
class TraceExceptionLogger : ExceptionLogger
{
public override void LogCore(ExceptionLoggerContext context)
{
Trace.TraceError(context.ExceptionContext.Exception.ToString());
}
}
在发布更多细节指出此处的http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-21#global-error
这篇关于我如何成立的WebAPI一个全球性的错误处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!