【发布时间】:2013-12-17 16:57:12
【问题描述】:
我想根据自定义参数“主题”设置打开视图的路线, 像这样:
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可以在我定义的路径中找到视图页面。但是路由仍然不接受url {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
但这并不完美,我仍然需要帮助或自己找到路。
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-4 routes