如何在WebApi中设置全局错误处理程序? [英] How do I set up a global error handler in WebApi?
问题描述
这是我的要求:
- 在操作方法以及其他地方捕获异常(例如控制器解析)。
- 在处理过程中可以访问原始的Exception对象。 li>
- 在错误处理过程中,可以访问我的(Autofac)IOC容器中的服务(这是一个很强的需求,但不一定有)。
- 否依赖于MVC(我使用纯WebApi)。不要依赖IIS是非常需要的。
如何设置这个?
如果您更新到Web API v2.1,可通过Nuget使用以下命令:
安装包Microsoft.AspNet.WebApi
您可以创建一个全局异常处理程序通过从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#全局错误
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.
Here are my requirements:
- Catch exceptions hit in action methods as well as in other places (e. g. controller resolution).
- Have access to the original Exception object during my handling.
- Have access to services in my (Autofac) IOC container during the error handling process (this is a strong want but not a must have).
- No dependency on MVC (I am using pure WebApi). No dependency on IIS is highly desirable.
How do I go about setting this up?
If you update to Web API v2.1, available via Nuget with this command:
Install-Package Microsoft.AspNet.WebApi
You can create a Global Exception Handler by inheriting from Exception Logger.
Here is an example:
class TraceExceptionLogger : ExceptionLogger
{
public override void LogCore(ExceptionLoggerContext context)
{
Trace.TraceError(context.ExceptionContext.Exception.ToString());
}
}
More details in the release notes here: http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-21#global-error
这篇关于如何在WebApi中设置全局错误处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!