ASP.NET Web API 2.1 includes a new global error handling capability. I found an example that demonstrates how to log exceptions into ELMAH. But I use NLog to log errors to a database table. Is it possible to use Web API global error handling with NLog? If so, please provide an example.
Global Exception Filters With exception filters, you can customize how your Web API handles several exceptions by writing the exception filter class. Exception filters catch the unhandled exceptions in Web API. When an action method throws an unhandled exception, execution of the filter occurs.
Use the UseExceptionHandler middleware in ASP.NET Core So, to implement the global exception handler, we can use the benefits of the ASP.NET Core build-in Middleware. A middleware is indicated as a software component inserted into the request processing pipeline which handles the requests and responses.
It's actually quite simple, you either implement IExceptionLogger
by hand or inherit from the base class, ExceptionLogger
.
public class NLogExceptionLogger : ExceptionLogger { private static readonly Logger Nlog = LogManager.GetCurrentClassLogger(); public override void Log(ExceptionLoggerContext context) { Nlog.LogException(LogLevel.Error, RequestToString(context.Request), context.Exception); } private static string RequestToString(HttpRequestMessage request) { var message = new StringBuilder(); if (request.Method != null) message.Append(request.Method); if (request.RequestUri != null) message.Append(" ").Append(request.RequestUri); return message.ToString(); } }
Also add it to the config:
var config = new HttpConfiguration(); config.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger());
You can find full sample solution here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With