gpt4 book ai didi

asp.net-mvc - 在 ASP.NET MVC 中覆盖 `HandleErrorAttribute`

转载 作者:行者123 更新时间:2023-12-05 01:26:57 27 4
gpt4 key购买 nike

我想用一个名为 HandleErrorsWithLogging 的新版本覆盖 HandleErrorAttribute。本质上,我希望它将未处理的异常记录到我的日志文件中,然后继续使用 HandleError 获得的典型“重定向到 ~/Shared/Error”功能。

我已经在 global.asax 中的所有操作中添加了 HandleError

这是最好的方法还是有更简单的方法来访问未处理的异常以进行日志记录?我还考虑过对 Error View 本身的 Ajax 调用。

最佳答案

您可以创建一个自定义过滤器,它继承自 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;
}
}
}

关于asp.net-mvc - 在 ASP.NET MVC 中覆盖 `HandleErrorAttribute`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6621454/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com