c# - 使用 NLog 在 ASP.NET Web API 2.1 中进行全局异常处理?

标签 c# asp.net asp.net-web-api error-handling nlog

ASP.NET Web API 2.1 包括一个新的 global error handling能力。我找到了一个 example这演示了如何将异常记录到 ELMAH 中。但是我用NLog将错误记录到数据库表中。是否可以将 Web API 全局错误处理与 NLog 一起使用?如果是,请提供示例。

最佳答案

其实很简单,要么自己实现IExceptionLogger,要么继承基类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();
    }
}

同时将其添加到配置中:

var config = new HttpConfiguration(); 

config.Services.Add(typeof(IExceptionLogger), new NLogExceptionLogger()); 

您可以找到完整的示例解决方案 here .

关于c# - 使用 NLog 在 ASP.NET Web API 2.1 中进行全局异常处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25865610/

相关文章:

c# - 使用 OData V4 客户端更新动态实体

c# - Web Api 2 中的 Mvc 样式参数绑定(bind)?

css - Winnovative pdf 转换器设计问题?

asp.net - 以下部分已定义但尚未为布局页面呈现 “~/Views/Shared/_Layout.cshtml” : “featured”

c# - 临时 block REST Controller

c# sql 返回没有时间的日期

c# - SharpZipLib - 将 ZipEntry 添加到 ZipFile 会引发 ZipException

c# - 使用 select 将 foreach 转换为 linq 表达式

.net - asp.net网站中的CSS文件

c# - ASP.NET WebForms 中的字符串与控件