2

I need to log exceptions from an ApiController.

After installing Elmah.MVC I can log 404 error and other in DB, but exceptions in ApiController do not show ups in Elmah.

Any idea how to fix that?

  <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);   
    }
}
1

2 Answers 2

7

There's a NuGet package for that: http://www.nuget.org/packages/Elmah.Contrib.WebApi/

After install you need to add a new global filter as explained here: http://blog.elmah.io/logging-to-elmah-io-from-web-api/ (just install the Elmah.Contrib.WebApi package without elmah.io).

Sign up to request clarification or add additional context in comments.

Comments

1

I have solve my issue creating a custom attribute for Elmah and adding it to 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()
        );

    }
}

1 Comment

Do you already have HandleErrorAttribute registered in global filters?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.