如何在ASP.NET Web API中设置Elmah

37

我尝试了许多 elmah nuget,但它们都不能与 ASP.NET Web API 一起使用。有人知道原因吗?是否有任何解决方法?

4个回答

24

使用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.aspxhttp://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服务器错误显示自定义错误信息,你可以在Web API中实现新的ExceptionHandler(注意ExceptionHandler和ExceptionLogger是不同的)。

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


谢谢,伙计。这很有帮助。我还在琢磨怎么在我的情况下(WebApi也在MVC站点的上下文中运行)使它工作,直到我想到安装Elmah.MVC包。我在我的博客文章中稍微详细地介绍了一下:http://dbarrowstechblog.blogspot.co.uk/2015/03/elmah-aspnet-webapi-tip.html - David Barrows
1
第一个(简单)解决方案直接调用 Elmah.ErrorLog.GetDefault(HttpContext.Current).Log 可以正常工作,但它不会发送电子邮件(如果您已经设置了 Elmah),只是记录日志。如果您希望按照 web.config 中指定的方式由 Elmah 处理异常,则建议将 .Log 调用替换为 Elmah.ErrorSignal.FromCurrentContext().Raise(context.Exception);,这将触发正常的 Elmah 处理。 - Greg

16

一种选择是设置自定义ExceptionFilterAttribute,重写OnException方法,并从那里向Elmah发送信号。请参见下面的示例链接

Elmah WebAPI 示例


我遇到的问题(并且仍然没有时间解决)是在我的elmah访问上使用表单身份验证,同时在我的api上使用基本身份验证。 - Antony Scott

13

请查看下面的链接,其中详细描述了如何在Web API中使用elmah:

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

使用方法:

Simply register it during your application's start up, or on a controller-by-controller basis.

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

    ...
}

(来自Elmah.Contrib.WebApi GitHub仓库)


这对我有用,应该被接受的解决方案。 - tschan

4

对于ASP.NET Web API,请使用Elmah.MVC nuget包,下面给出了详细信息。

摘自:如何设置ELMAH.MVC与ASP.NET MVC 4?

什么是Elmah?

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

为什么要使用Elmah?

ELMAH作为未处理的ASP.NET异常的不显眼的拦截器,通常会表现为ASP.NET 黄色屏幕死亡

现在我们知道了什么是Elmah以及为什么要使用Elmah,让我们快速开始学习如何将Elmah与您的ASP.NET MVC项目一起使用。

步骤1:右键单击您的解决方案,选择“管理NuGet程序包”选项 enter image description here 步骤2:在NuGet程序包管理器中搜索“Elmah”,并安装Elmah.MVC NuGet扩展。 enter image description here NuGet程序包管理器将下载并添加所需的dll,并修改web.config的<appSetting>以使Elmah正常工作。

步骤三:完成了!!您的 Elmah 现在已准备好测试。我已生成了一个 404 来测试我的 Elmah 是否有效,可以通过此 URL 访问 ELMAH:http://yourapp.com/elmahenter image description here enter image description here

希望能帮到您 :)

进一步阅读:


5
你是否从“ApiController”生成了404?如果不是,而是标准的MVC控制器,那么你完全错过了问题的要点。 - Sixten Otto
已从普通控制器生成了404错误,这只是一个例子,如果我使用WebAPI控制器并导致404错误,情况也将是相同的。 - Yasser Shaikh
15
你实际尝试过吗?因为我相当确定那不是事实。Web API 中的异常处理方式有所不同。 - Sixten Otto
@Doozer1979 说的是谁?你只需要在这里注册你的 HttpFilters,以下是如何操作的链接:https://dev59.com/52kw5IYBdhLWcg3wNXz2#10067886 - Yasser Shaikh
2
为什么不把这部分作为你的答案的一部分呢,而不是留下一些对OP的问题无效的东西。 - MrBliz
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接