[英]Bind route to custom physical path in mvc4
我想根據自定義參數“主題”設置打開視圖的路線,如下所示:
http://localhost/black/home to open ~/themes/black/views/home/index.cshtml
http://localhost/white/home to open ~/themes/white/views/home/index.cshtml
主題名稱是動態的,我注冊了這樣的路線:
routes.MapRoute("ThemeRoute", "{theme}/{controller}/{action}/{id}"
, new
{
theme = "default",
controller = "Home",
action = "Index",
id = UrlParameter.Optional
});
但這不起作用。 如何將自定義路由“ {theme} / {controller} / {action} / {id}”綁定到自定義物理路徑,例如“〜/ themes / {theme} / views / {view} / {action}”? 還是不可能? 如果有人可以給我建議,我將不勝感激。
更新:我反編譯了System.Web.Mvc.RazorViewEngine
類,並了解如何定義自己的自定義物理路徑,如下所示:
public sealed class ThemeViewEngine : RazorViewEngine
{
private ThemeViewEngine(IViewPageActivator viewPageActivator)
: base(viewPageActivator)
{
//...
AreaViewLocationFormats = new[]
{
"~/Areas/{2}/Themes/{3}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Themes/{3}/Views/Shared/{0}.cshtml",
"~/Areas/{2}/Views/{1}/{0}.cshtml",
"~/Areas/{2}/Views/Shared/{0}.cshtml"
};
//...
}
}
然后重寫方法FindView
並將引擎添加到Global.asax的ViewEngines.Engines
中,現在ViewEngine可以在我定義的路徑中查找視圖頁面了。但是該路線仍然不接受網址{theme}/{controller}/{action}/{id}
,似乎路由無法識別{theme}是具有相同名稱的引擎。 所以我現在使用查詢字符串和cookie來控制主題,如下所示:
http://localhost/home?theme=black to open ~/themes/black/views/home/index.cshtml
http://localhost/home?theme=white to open ~/themes/white/views/home/index.cshtml
但這不是完美的,我仍然需要幫助或自己尋找方法。
如何使用Areas組織兩個主題。 您可以有兩個區域:“黑色”和“白色”。 他們每個人都有自己的控制器和動作。 路由模式為:{AreaName} / {Controller} / {Action} / {Id}。 檢查此鏈接以了解如何使用區域。 http://www.codeguru.com/csharp/.net/net_asp/mvc/article.php/c20227/Using-Areas-in-ASPNET-MVC-Application.htm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.