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和异常处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:ASP.NET Web API 2:ExceptionLogger和异常处理程序
 
				
         
 
            
        
             猜你喜欢
        
	     - WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
 
						 
						 
						 
						 
						 
				 
				 
				 
				