ASP.NET Web API 2:ExceptionLogger和异常处理程序

ASP.NET Web API 2: ExceptionLogger and Exception Handler(ASP.NET Web API 2:ExceptionLogger和异常处理程序)
本文介绍了ASP.NET Web API 2:ExceptionLogger和异常处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在web API中实现全局异常日志记录,并使用该错误ID向用户发送一条友好的消息,这样他就可以带着错误ID返回给我们,这样我们就可以修复它。我两个都在实现:

  • System.Web.Http.ExceptionHandling.ExceptionLogger
  • System.Web.Http.ExceptionHandling.ExceptionHandler

下面是覆盖ExceptionLogger抽象类的类:

public class GlobalExceptionLogger : System.Web.Http.ExceptionHandling.ExceptionLogger
{
    public override void Log(ExceptionLoggerContext context)
    {
        LogMessage logMsg = new LogMessage();
        logMsg.ID = System.Guid.NewGuid().ToString();
        logMsg.MessageType = MessageType.ResourceServerAPI;
        logMsg.SenderMethod = context.Request.RequestUri != null ? string.Format("Request URL: {0}", context.Request.RequestUri.ToString()) : "";
        logMsg.Level = MesageLevel.Error;
        logMsg.MachineName = Environment.MachineName;
        logMsg.Message = context.Exception.Message;

        Logger.LogError(logMsg);
    }
}

以下是我处理错误的方式:

public class GlobalExceptionHandler : System.Web.Http.ExceptionHandling.ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        var metadata = new ErrorData
        {
            Message = "An error occurred! Please use the ticket ID to contact our support",
            DateTime = DateTime.Now,
            RequestUri = context.Request.RequestUri,
            ErrorId = //get the ID already logged
        };

        var response = context.Request.CreateResponse(HttpStatusCode.InternalServerError, metadata);
        context.Result = new ResponseMessageResult(response);        
    }
}

由于异常日志记录发生在处理之前,将ID从异常记录器传递到异常处理程序以向最终用户发送相应的错误ID的最佳方式是什么?

推荐答案

您可以将其添加到HttpRequestMessage.Properties

public static class HttpRequestMessageExtensions
{
    private const string LogId = "LOG_ID";

    public static void SetLogId(this HttpRequestMessage request, Guid id)
    {
        request.Properties[LogId] = id;
    }

    public static Guid GetLogId(this HttpRequestMessage request)
    {
        object value;
        if (request.Properties.TryGetValue(LogId, out value))
        {
            return (Guid) value;
        }

        return Guid.Empty;
    }
}

然后在记录器/处理程序中使用这些扩展方法:

public class GlobalExceptionLogger : System.Web.Http.ExceptionHandling.ExceptionLogger
{
    public override void Log(ExceptionLoggerContext context)
    {
        LogMessage logMsg = new LogMessage();
        logMsg.ID = System.Guid.NewGuid().ToString();
        logMsg.MessageType = MessageType.ResourceServerAPI;
        logMsg.SenderMethod = context.Request.RequestUri != null ? string.Format("Request URL: {0}", context.Request.RequestUri.ToString()) : "";
        logMsg.Level = MesageLevel.Error;
        logMsg.MachineName = Environment.MachineName;
        logMsg.Message = context.Exception.Message;

        // Set the ID
        context.Request.SetLogId(logMsg.ID);

        Logger.LogError(logMsg);
    }
}

public class GlobalExceptionHandler : System.Web.Http.ExceptionHandling.ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        // Get the ID
        var id = context.Request.GetLogId();

        var metadata = new ErrorData
        {
            Message = "An error occurred! Please use the ticket ID to contact our support",
            DateTime = DateTime.Now,
            RequestUri = context.Request.RequestUri,
            ErrorId = id

        };

        var response = context.Request.CreateResponse(HttpStatusCode.InternalServerError, metadata);
        context.Result = new ResponseMessageResult(response);
    }
}

这篇关于ASP.NET Web API 2:ExceptionLogger和异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)