【问题标题】:Error handling and logging in ASP.NETASP.NET 中的错误处理和日志记录
【发布时间】:2014-03-05 09:20:21
【问题描述】:
我对包含 MVC 5 页面和 WebApi 2 服务的 Web 应用程序有以下要求:
所有错误(404、500、“从客户端检测到具有潜在危险的 Request.Form 值”)都应生成相应的错误页面(无浏览器重定向,保留用户在地址栏中输入的 URL )。
所有错误页面都应使用动态 MVC 视图呈现并包含唯一 ID,用户可以将其提供给电话支持。
必须记录所有错误,日志条目应包含提供给用户的 ID。
为不同的异常生成不同的错误页面,例如/error/NoSignal 表示 NoSignalException。
这可行吗?
【问题讨论】:
标签:
asp.net-mvc
asp.net-web-api
【解决方案1】:
我会覆盖异常挂起方法 - 在每个控制器或基础中(取决于您的决定)。
protected override void OnException(ExceptionContext filterContext)
{
filterContext.Exception.ToString(); // - make any checks here
// If method is not implemented
if (filterContext.Exception.GetType() == typeof(NotImplementedException))
{
filterContext.Result = new ViewResult { ViewName = "NotImplemented" };
filterContext.ExceptionHandled = true;
}
}