如何在ApiController上使用Elmah.MVC?

时间:2014-06-17 07:05:19

标签: c# asp.net-mvc elmah elmah.mvc

我需要记录ApiController的异常。

安装Elmah.MVC后,我可以在DB中记录404错误和其他错误,但ApiController中的异常不会显示在Elmah中。

知道如何解决这个问题吗?

  <modules>
      <remove name="FormsAuthenticationModule" />
      <add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" preCondition="managedHandler" />
      <add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" preCondition="managedHandler" />
    </modules>

  <elmah>
    <security allowRemoteAccess="yes" />
    <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="XXX"/>
  </elmah>



    public class StatusController : ApiController
{
    private StatusBLL statusBLL = new StatusBLL();

    // POST api/status
    public void Post(StatusDTO status)
    {
        throw new ArgumentException("test elmah here");
        if (!statusBLL.Register(status))
            helpers.BusinessLayer.CreateResponseApiMessage(statusBLL.Errors);   
    }
}

2 个答案:

答案 0 :(得分:7)

有一个NuGet包:http://www.nuget.org/packages/Elmah.Contrib.WebApi/

安装完成后,您需要添加一个新的全局过滤器,如下所述:http://blog.elmah.io/logging-to-elmah-io-from-web-api/(只需安装不带elmah.io的Elmah.Contrib.WebApi软件包)。

答案 1 :(得分:1)

我已经解决了我为Elmah创建自定义属性并将其添加到Global.asax.cs的问题

public class ElmahErrorAttribute : ExceptionFilterAttribute
{
    public override void OnException(
        System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
    {

        if (actionExecutedContext.Exception != null)
            Elmah.ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);

        base.OnException(actionExecutedContext);
    }
}


public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register); // WebApi
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        Configure(System.Web.Http.GlobalConfiguration.Configuration);
    }
    private void Configure(HttpConfiguration httpConfiguration)
    {
        httpConfiguration.Filters.Add(
            new ElmahErrorAttribute()
        );

    }
}