How to set up Elmah with ASP.NET Web API

醉酒当歌 提交于 2020-01-22 04:51:13

问题


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?


回答1:


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




回答2:


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




回答3:


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)




回答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

Step 2: In the Nuget Package manager search for "Elmah" and install the Elmah.MVC nuget extension.

The Nuget Package manager will download and add the required dlls and modify the web.config's <appSetting> for Elmah to wo

rk.

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.

Hope this helps :)

Further Reading :

  • Elmah on code.google.com
  • Elmah.MVC 2.0.2 on Nuget
  • Elmah.MVC on GitHub


来源:https://stackoverflow.com/questions/10116593/how-to-set-up-elmah-with-asp-net-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!