小编Tai*_*deh的帖子

OWIN中间件中的全局异常处理

我正在尝试在构建于OWIN中间件(使用Owin.Host.SystemWeb的IIS HOST)之上的ASP.NET Web API 2.1项目中创建统一的错误处理/报告.目前我使用了一个自定义异常记录器,它继承System.Web.Http.ExceptionHandling.ExceptionLogger并使用NLog记录所有异常,如下面的代码所示:

public class NLogExceptionLogger : ExceptionLogger
{

    private static readonly Logger Nlog = LogManager.GetCurrentClassLogger();
    public override void Log(ExceptionLoggerContext context)
    {
       //Log using NLog
    } 
}
Run Code Online (Sandbox Code Playgroud)

我想将所有API异常的响应主体更改为友好的统一响应,该响应使用System.Web.Http.ExceptionHandling.ExceptionHandler以下代码隐藏所有异常详细信息:

public class ContentNegotiatedExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        var errorDataModel = new ErrorDataModel
        {
            Message = "Internal server error occurred, error has been reported!",
            Details = context.Exception.Message,
            ErrorReference = context.Exception.Data["ErrorReference"] != null ? context.Exception.Data["ErrorReference"].ToString() : string.Empty,
            DateTime = DateTime.UtcNow
        };

        var response …
Run Code Online (Sandbox Code Playgroud)

asp.net-web-api owin katana asp.net-web-api2 owin-middleware

32
推荐指数
2
解决办法
2万
查看次数