在ActionFilterAttribute.OnActionExecuted中设置布局是有问题的

Kaa*_*aan 12 c# asp.net asp.net-mvc asp.net-mvc-4 razorgenerator

我正在尝试在ActionFilterAttribute我编写的自定义中设置布局路径,如下所示:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = "~/Views/Layouts/Test.cshtml"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,Test.cshtml是RazorGenerator在不同项目中的预编译视图(借助于).

但它给了我错误:

未找到视图"索引"或其主数据或视图引擎不支持搜索的位置.以下地点搜索:〜/查看/主页/ Index.cshtml〜/查看/共享/ Index.cshtml〜/浏览/首页/ Index.aspx的〜/浏览/首页/ Index.ascx〜/查看/共享/索引. aspx~/Views/Shared/Index.ascx~/Views/Layouts/Test.cshtml

和控制器实际上很简单:

[LayoutInjecter]
public class HomeController : Controller
{
    public ActionResult Index()
    {
       return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

Ami*_*rzi 7

错误显示LayoutInjecter工作正常.你说:

在这里,Test.cshtml是在不同项目中的预编译视图.

但是,不支持使用来自不同(来自Web项目外部)的剃刀视图.然而,有一个预编译剃刀视图的工具,然后你可以把它们放在任何调用RazorGenerator的 DLL中. 编译器找不到指定的主布局文件并显示此错误.

有关更多信息,请查看

编辑:PrecompiledMvc​​ViewEngine如何知道要渲染哪个视图?

PrecompiledMvcViewEngine 仍然依赖于ASP.NET MVC Views文件夹约定,使用相对文件路径来定位视图.但是,这有点误导.在PrecompiledMvcViewEngine 不看物理文件 ; 它寻找System.Web.WebPages.PageVirtualPathAttributeRazor单文件生成器添加到它生成的每个视图,包括视图的相对文件路径.

编辑2:我相信您的问题的指导将在GitHub找到.


Cat*_*lin 4

有用。确保布局路径"~/Views/Layouts/Test.cshtml"正确。

另外,请确保“Test.cshtml”是布局页面,而不是视图/部分视图。