编程语言
首页 > 编程语言> > C#-ASP.NET Web API 2:ExceptionLogger和异常处理程序

C#-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);
    }
}

标签:error-handling,asp-net-web-api2,exception-handling,c
来源: https://codeday.me/bug/20191118/2025901.html