Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
54 views
in Technique[技术] by (71.8m points)

How to set up Elmah with ASP.NET Web API

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?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...