如何使用ASP.NET Web API设置Elmah

时间:2012-04-12 02:23:17

标签: asp.net-web-api elmah

我尝试了很多elmah nugets,但是他们没有使用ASP.NET Web API。有人知道为什么吗?对此有什么解决方法吗?

4 个答案:

答案 0 :(得分:22)

使用ELMAH捕获WEB API中的异常有两种选择。

如果要捕获“操作和控制器”中遇到的错误,即在业务逻辑中,您可以创建一个ActionFilterAttribute并将这些例外记录到ELMAH。

示例:

public class UnhandledExceptionFilter : ExceptionFilterAttribute {
    public override void OnException(HttpActionExecutedContext context) {
        Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(context.Exception));
    }
}

然后通过添加该过滤器进行连线。

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Filters.Add(new UnhandledExceptionFilter());
    }
}

使用上述方法,将无法处理以下错误:

  • 从控制器构造函数抛出的异常。
  • 从消息处理程序抛出的异常。
  • 路由期间抛出的异常。
  • 响应内容序列化期间抛出的异常

参考:http://blogs.msdn.com/b/webdev/archive/2012/11/16/capturing-unhandled-exceptions-in-asp-net-web-api-s-with-elmah.aspx& http://www.asp.net/web-api/overview/error-handling/web-api-global-error-handling

为了让ELMAH在全局级别记录 WEB API错误,以便捕获所有500个服务器错误,请执行以下操作:

安装nuget:https://www.nuget.org/packages/Elmah.Contrib.WebApi/

将以下内容添加到WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ...
        config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());
        ...
    }
}

如果您想显示500 Server错误的自定义错误消息,您可以在Web Api中实现新的ExceptionHandler(请注意,ExceptionLogger和ExceptionHandler是不同的。)

class OopsExceptionHandler : ExceptionHandler
{
    public override void HandleCore(ExceptionHandlerContext context)
    {
        context.Result = new TextPlainErrorResult
        {
            Request = context.ExceptionContext.Request,
            Content = "Oops! Sorry! Something went wrong." +
                      "Please contact support@contoso.com so we can try to fix it."
        };
    }

    private class TextPlainErrorResult : IHttpActionResult
    {
        public HttpRequestMessage Request { get; set; }

        public string Content { get; set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response = 
                             new HttpResponseMessage(HttpStatusCode.InternalServerError);
            response.Content = new StringContent(Content);
            response.RequestMessage = Request;
            return Task.FromResult(response);
        }
    }
}

参考:http://www.asp.net/web-api/overview/error-handling/web-api-global-error-handling

答案 1 :(得分:15)

一个选项是设置自定义ExceptionFilterAttribute,覆盖OnException方法,并从那里发出Elmah信号。请参阅下面的示例链接

Elmah WebAPI Sample

答案 2 :(得分:10)

检查下面描述的URL,详细说明如何将elmah与Web API一起使用:

http://blogs.msdn.com/b/webdev/archive/2012/11/16/capturing-unhandled-exceptions-in-asp-net-web-api-s-with-elmah.aspx

您还可以使用下面的NuGet包:

Install-Package Elmah.Contrib.WebApi

用法:

  

只需在应用程序启动期间或逐个控制器上注册它。

     
protected void Application_Start()
{
    GlobalConfiguration.Configuration.Filters.Add(new ElmahHandleErrorApiAttribute());

    ...
}

(来自the Elmah.Contrib.WebApi GitHub repo

答案 3 :(得分:7)

对于ASP.NET Web API,请使用Elmah.MVC nuget包,其详细信息如下所示

取自:HOW TO SETUP ELMAH.MVC WITH ASP.NET MVC 4 ?

什么是Elmah?

ELMAH是一个开源项目,其目的是在ASP.NET Web应用程序中记录和报告未处理的异常。

为什么要使用Elmah?

ELMAH是一个不显眼的ASP.NET异常拦截器,通常用ASP.NET yellow screen of death表示。

现在我们知道使用Elmah的原因和原因,让我们快速了解如何在您的ASP.NET MVC项目中使用Elmah。

第1步:右键单击您的解决方案并选择“管理Nuget包”选项enter image description here

第2步:在Nuget包管理器中搜索“Elmah”并安装Elmah.MVC nuget扩展程序。 enter image description here Nuget包管理器将下载并添加所需的dll,并将elmah的web.config <appSetting>修改为wo enter image description here rk。

第3步:就是这样!你的Elmah现在准备好测试了。我已经生成了404来测试我的Elmah是否正常工作,可以通过以下网址访问ELMAH: http://yourapp.com/elmah enter image description here enter image description here

希望这会有所帮助:)

进一步阅读: