如何在WebApi中设置全局错误处理程序? [英] How do I set up a global error handler in WebApi?

查看:137
本文介绍了如何在WebApi中设置全局错误处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个.NET 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆