37

I've tried many elmah nugets but they didn't work with ASP.NET Web API. Does anybody knows why? Is there any work around for that?

LeftyX
  • 35,328
  • 21
  • 132
  • 193

4 Answers4

24

There are two options by using ELMAH to capture exceptions in WEB API.

If you want to capture errors that are encountered in Actions and Controllers , i.e. in your business logic you can create a ActionFilterAttribute and log those exceptions to ELMAH.

example:

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

Then wireup by adding that filter.

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

With the above approach following errors will not be handled:

  • Exceptions thrown from controller constructors.
  • Exceptions thrown from message handlers.
  • Exceptions thrown during routing.
  • Exceptions thrown during response content serialization

Reference: 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

In order for ELMAH to log WEB API errors at the global level such that all 500 Server errors are caught then do this:

Install nuget: https://www.nuget.org/packages/Elmah.Contrib.WebApi/

Add the below to WebApiConfig

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

And if you want to show custom error messages for the 500 Server errors you can implement the new ExceptionHandler in Web Api (Note that ExceptionLogger and ExceptionHandler are different.)

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

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

Scott Weldon
  • 9,673
  • 6
  • 48
  • 67
jaxxbo
  • 7,314
  • 4
  • 35
  • 48
  • thanks mate, this was helpful. I was still scratching my head for a bit 'til I figured out how to make it work in my situation (where the WebApi is also running in the context of an MVC site); the answer was simply to also install the Elmah.MVC package. I expand on that slightly on my blog post here: http://dbarrowstechblog.blogspot.co.uk/2015/03/elmah-aspnet-webapi-tip.html – David Barrows Mar 19 '15 at 20:55
  • 1
    The first (simple) solution that directly calls `Elmah.ErrorLog.GetDefault(HttpContext.Current).Log` works fine, but it doesn't send an email (if that's how you've got Elmah set up) - it just logs. If you want your exception handled by Elmah in the manner you've specified in web.config, then I'd suggest replacing the .Log call with `Elmah.ErrorSignal.FromCurrentContext().Raise(context.Exception);` which will trigger the normal Elmah handling. – Greg Jul 28 '17 at 13:30
16

one option would be to setup a custom ExceptionFilterAttribute, override the OnException method, and signal Elmah from there. See the sample link below

Elmah WebAPI Sample

cecilphillip
  • 11,446
  • 4
  • 36
  • 40
  • The thing I struggled with (and still haven't found the time to address) is having forms authentication on my elmah access mixed with basic auth on my api – Antony Scott Apr 12 '12 at 06:10
13

Check the below URL it describe in details how to use elmah with Web API:

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

You can also use the NuGet Package below:

Install-Package Elmah.Contrib.WebApi

Usage:

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());

    ...
}

(from the Elmah.Contrib.WebApi GitHub repo)

Scott Weldon
  • 9,673
  • 6
  • 48
  • 67
Ahmed Ahmed
  • 1,036
  • 11
  • 16
4

For ASP.NET Web API use the Elmah.MVC nuget package, details of which are given below

Taken from : HOW TO SETUP ELMAH.MVC WITH ASP.NET MVC 4 ?

What is Elmah ?

ELMAH is an open source project whose purpose is to log and report unhandled exceptions in ASP.NET web applications.

Why to use Elmah ?

ELMAH serves as an unobtrusive interceptor of unhandled ASP.NET exceptions, those usually manifesting with the ASP.NET yellow screen of death.

So now we know what and why to use Elmah, Lets quickly get started on how to use Elmah with your ASP.NET MVC project.

Step 1: Right click on your solution and select the "Manage Nuget Packages" option enter image description here

Step 2: In the Nuget Package manager search for "Elmah" and install the Elmah.MVC nuget extension. enter image description here The Nuget Package manager will download and add the required dlls and modify the web.config's <appSetting> for Elmah to woenter image description hererk.

Step 3: That's it !! Your Elmah is now ready to test. I have generated a 404 to test if my Elmah works, ELMAH can be accessed by this url : http://yourapp.com/elmah. enter image description here enter image description here

Hope this helps :)

Further Reading :

Community
  • 1
  • 1
Yasser Shaikh
  • 46,934
  • 46
  • 204
  • 281
  • 5
    And are you generating that 404 from an `ApiController`? If not, and it's a standard MVC controller, you've missed the point of the question completely. – Sixten Otto Sep 20 '13 at 23:50
  • Have generated 404 from a normal controller, this is just an example, same would have been the case had i used the webapi controller and cause a 404. – Yasser Shaikh Sep 23 '13 at 05:16
  • 15
    Have you actually tried it? Because I'm pretty sure that's not the case. Exception handling works differently in Web API. – Sixten Otto Sep 23 '13 at 05:34
  • @Doozer1979 said who ? You just need to register your `HttpFilters` here is how to do it http://stackoverflow.com/questions/10059563/elmah-and-api-controller-in-mvc4-not-logging-errors/10067886#10067886 – Yasser Shaikh Sep 24 '14 at 05:49
  • 2
    Well, why not make that part of your answer then, instead of leaving something up which doesn't work for the OP's question. – MrBliz Sep 24 '14 at 09:05
  • So does this solution work or not? I am wanting to implement elmah into my web api project. This is a very well answered post except it missed the point slightly. – Zapnologica May 26 '15 at 20:55
  • @Zapnologica This answer + http://stackoverflow.com/a/13264550/1182982 will help you for sure :) – Yasser Shaikh May 27 '15 at 06:17