How to set up Elmah with ASP.NET Web API

前端 未结 4 2067
忘了有多久
忘了有多久 2021-01-31 08:18

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?

相关标签:
4条回答
  • 2021-01-31 08:49

    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

    0 讨论(0)
  • 2021-01-31 08:52

    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 :

    • Elmah on code.google.com
    • Elmah.MVC 2.0.2 on Nuget
    • Elmah.MVC on GitHub
    0 讨论(0)
  • 2021-01-31 08:56

    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)

    0 讨论(0)
  • 2021-01-31 09:10

    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

    0 讨论(0)
提交回复
热议问题