Gle*_*rie 2 error-handling asp.net-mvc logging
我想覆盖HandleErrorAttribute一个名为类似的新版本HandleErrorsWithLogging.本质上,我希望它将未处理的异常记录到我的日志文件中,然后继续执行典型的" 重定向到〜/共享/错误 "功能HandleError.
我已经HandleError在我的所有行动中添加了global.asax
这是最好的方法还是有一些更简单的方法来获取对日志记录的未处理异常的访问权限?我还有关于Error视图本身的Ajax调用.
小智 6
您可以创建从FilterAttribute继承并实现IExceptionFilter的自定义筛选器.然后在global.asax.cs中注册它.您还必须在web.config中启用自定义错误处理:
<customErrors mode="On"/>
public class HandleErrorAndLogExceptionAttribute : FilterAttribute, IExceptionFilter
{
/// <summary>
/// The method called when an exception happens
/// </summary>
/// <param name="filterContext">The exception context</param>
public void OnException(ExceptionContext filterContext)
{
if (filterContext != null && filterContext.HttpContext != null)
{
if (!filterContext.IsChildAction && (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled))
{
// Log and email the exception. This is using Log4net as logging tool
Logger.LogError("There was an error", filterContext.Exception);
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
// Set the error view to be shown
ViewResult result = new ViewResult
{
ViewName = "Error",
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
result.ViewData["Description"] = filterContext.Controller.ViewBag.Description;
filterContext.Result = result;
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
}
Run Code Online (Sandbox Code Playgroud)