[英]How to test ActionFilterAttribute - OnActionExecuted
[英]Setting Layout in ActionFilterAttribute.OnActionExecuted is problematic
我正在嘗試在我編寫的自定義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"
}
}
}
在這里Test.cshtml是預編譯的視圖(的幫助下RazorGenerator
在不同的項目)。
但它給了我錯誤:
未找到視圖“索引”或其主數據或視圖引擎不支持搜索的位置。 搜索了以下位置:〜/ Views / Home / Index.cshtml~ / Views / Shared / Index.cshtml~ / Views / Home / Index.aspx~ / Views / Home / Index.ascx~ / Views / Shared / Index。 aspx~ / Views / Shared / Index.ascx~ / Views / Layouts / Test.cshtml
和控制器實際上很簡單:
[LayoutInjecter]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
錯誤顯示LayoutInjecter
工作正常。 你說:
在這里,Test.cshtml是在不同項目中的預編譯視圖。
但是 ,不支持使用來自不同(來自Web項目外部)的剃刀視圖。 然而,有一個預編譯剃刀視圖的工具,然后你可以把它們放在任何調用RazorGenerator的 DLL中。 編譯器找不到指定的主布局文件並顯示此錯誤。
有關更多信息,請查看
編輯:PrecompiledMvcViewEngine如何知道要渲染哪個視圖?
PrecompiledMvcViewEngine
仍然依賴於ASP.NET MVC Views文件夾約定 ,使用相對文件路徑來定位視圖。 但是,這有點誤導。 PrecompiledMvcViewEngine
不查看物理文件 ; 它查找Razor單文件生成器添加到它生成的每個視圖的System.Web.WebPages.PageVirtualPathAttribute
,其中包含視圖的相對文件路徑。
有用。 確保布局路徑"~/Views/Layouts/Test.cshtml"
正確無誤。
另外,請確保“Test.cshtml”是布局頁面,而不是視圖/局部視圖。
將result.MasterName = "~/Views/Layouts/Test.cshtml"
更改為result.MasterName ="~/Views/Shared/Test.cshtml"
。 按照慣例,框架在您的asp.net mvc解決方案的〜/ Views / Shared /目錄中查找布局頁面。 在我看來,您是動態地或在運行時選擇母版頁。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.