gpt4 book ai didi

asp.net-mvc - 如何将 ViewData 传递给 HandleError View ?

转载 作者:行者123 更新时间:2023-12-03 21:27:31 25 4
gpt4 key购买 nike

在我的 Site.Master 文件中,我有 3 个简单的 ViewData 参数(整个解决方案中只有 3 个)。这些 ViewData 值对于我的应用程序中的每个页面都至关重要。由于在我的 Site.Master 中使用了这些值,因此我创建了一个抽象的 SiteController 类,该类覆盖 OnActionExecuting 方法来为解决方案中每个 Controller 上的每个 Action 方法填充这些值。

[HandleError(ExceptionType=typeof(MyException), View="MyErrorView")]
public abstract class SiteController : Controller
{
protected override void OnActionExecuting(...)
{
ViewData["Theme"] = "BlueTheme";
ViewData["SiteName"] = "Company XYZ Web Portal";
ViewData["HeaderMessage"] = "Some message...";

base.OnActionExecuting(filterContext);

}
}

我面临的问题是,当 HandleErrorAttribute 从 SiteController 类级别属性启动时,这些值没有传递给 MyErrorView(以及最终的 Site.Master)。这是一个简单的场景来显示我的问题:
public class TestingController : SiteController
{
public ActionResult DoSomething()
{
throw new MyException("pwnd!");
}
}

我也尝试通过覆盖我的 SiteController 中的 OnException() 方法来填充 ViewData 参数,但无济于事。 :(

在这种情况下,将 ViewData 参数传递给我的 Site.Master 的最佳方法是什么?

最佳答案

这是因为 HandleErrorAttribute 会在发生错误时更改传递给 View 的 ViewData。它传递一个 HandleErrorInfo 类的实例,其中包含有关 Exception、Controller 和 Action 的信息。

你可以做的是用下面实现的属性替换这个属性:

using System;
using System.Web;
using System.Web.Mvc;

public class MyHandleErrorAttribute : HandleErrorAttribute {

public override void OnException(ExceptionContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled)
{
Exception innerException = filterContext.Exception;
if ((new HttpException(null, innerException).GetHttpCode() == 500) && this.ExceptionType.IsInstanceOfType(innerException))
{
string controllerName = (string) filterContext.RouteData.Values["controller"];
string actionName = (string) filterContext.RouteData.Values["action"];
// Preserve old ViewData here
var viewData = new ViewDataDictionary<HandleErrorInfo>(filterContext.Controller.ViewData);
// Set the Exception information model here
viewData.Model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult { ViewName = this.View, MasterName = this.Master, ViewData = viewData, TempData = filterContext.Controller.TempData };
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
}
}

关于asp.net-mvc - 如何将 ViewData 传递给 HandleError View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1794936/

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