如何在不将异常标记为已处理的情况下重新路由异常

How to re-route exception without marking Exception as handled

基本上,当我的应用程序出现未处理的异常时,我希望它被 IIS 记录为未处理的异常(例如,以便可以在事件查看器中看到它),但我也想将用户引导至错误控制器。

我已经重写了控制器的 OnException 方法,以便将用户引导至自定义错误页面。问题的症结在于这段代码:

    protected override void OnException(ExceptionContext filterContext)
    {
        filterContext.Result = RedirectToAction("GeneralError", "Error", new{ routeValueA = "some value", routeValueB = "some other value"});
        filterContext.ExceptionHandled = false;
    }

我的问题是这样的:如果我设置 filterContext.ExceptionHandled = false 然后我得到一个黄色的死亡屏幕,而不是被重新路由到我的错误处理控制器。如果我设置 filterContext.ExceptionHandled = true 然后我会重新路由,但异常不会记录为未处理的异常。

我知道我可以使用 web.config 设置静态错误页面,但我 不想 这样做,因为那样我就不能使用路由将数据动态发送到我的错误控制器的值。

我可以在不标记 filterContext.ExceptionHandled= true 的情况下成功地将结果设置为我的 filterContext.Result 吗?

尝试关注 this 来源

protected override void OnException(ExceptionContext filterContext)
{
    if (filterContext.ExceptionHandled)
    {
        return;
    }
    filterContext.Result = new ViewResult
    {
        ViewName = "~/Views/Shared/Error.aspx"
    };
    filterContext.ExceptionHandled = true;
}

或者你也可以试试这个

web.config中设置custom errors如下:

<customErrors mode="On" defaultRedirect="~/Error">
  <error redirect="~/Error/NotFound" statusCode="404" />
  <error redirect="~/Error/UnauthorizedAccess" statusCode="403"/>
</customErrors>

你的 ErrorController:

public class ErrorController : Controller
{
    public ViewResult Index()
    {
        return View("Error");
    }
    public ViewResult NotFound()
    {
        Response.StatusCode = 404;  //you may want to set this to 200
        return View("NotFound");
    }
    public ViewResult UnauthorizedAccess()
    {
        Response.StatusCode = 404;  //you may want to set this to 200
        return View("UnauthorizedAccess");
    }
}

FilterConfigclass中将HandleErrorAttribute注册为全局动作过滤器,如下所示:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
     filters.Add(new CustomHandleErrorAttribute());
     filters.Add(new AuthorizeAttribute());
}

更新

我建议您阅读 this answer,因为它提供了您提出的问题的完整细节,我希望您能在那里找到一个好的解决方案!!

我相信您正在寻找的是您可以在 web.config 文件中设置的自定义错误页面,并告诉 IIS 重定向到自定义错误页面而不是默认页面(正如您所说的黄页)死亡 :) ) 对于任何未处理的异常。

这可能会有所帮助: How to make custom error pages work in ASP.NET MVC 4