【发布时间】:2026-01-28 19:05:01
【问题描述】:
这是对这个旧错误的新转折。我的许多页面都使用布局页面,所以它们在顶部附近有这个
@{
Layout = "~/Views/Shared/" + ViewBag.layout;
}
viewbag 布局在应用于控制器的动作过滤器中设置
namespace somenamespace.Controllers {
[SessionSettings]
public class MyController : Controller {
动作过滤器在哪里做这个
public class SessionSettings : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext filterContext) {
dynamic viewBag = filterContext.Controller.ViewBag;
string layout = some database lookup
if (layout == null) layout = "_defaultLayout.cshtml";
viewBag.layout = layout
这在大多数情况下都非常有效。但是当我检查事件日志 - 应用程序 - 我看到警告,事件 ID 1309,事件代码 3005,“发生未处理的异常”“在以下路径中找不到布局页面“~/Views/Shared/”: “~/Views/Shared/”。”
这是最重要的,通常事件发生在不使用布局的页面上,他们在顶部有这个
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>...
有人对此有任何想法吗?谢谢
【问题讨论】:
-
你调试它并观看 ViewBag.layout 了吗?也许试试:
Layout = "~/Views/Shared/" + ViewBag.layout ?? "" -
我想建议另一种方法:How to set a Razor layout in MVC via an attribute filter?,您可以使用传递自定义名称的选项扩展该属性。这样,只有在没有提供属性时才会使用 Viewstart。
-
W92 - 不幸的是,该错误从未在我的机器上发生过,并且在生产中它是间歇性的。
-
@Silvermind - 我对此进行了调查,基本上我正在做同样的事情。他们只是使用 OnResultExecuting 而不是 OnActionExecuting。为什么会有不同?
-
@nuander 它不会滥用 ViewBag 并且可以正常工作。
标签: c# asp.net-mvc