将路由绑定到mvc4中的自定义物理路径

时间:2013-12-02 03:59:49

标签: c# asp.net-mvc asp.net-mvc-4 routes

我想根据自定义参数“theme”设置打开视图的路径, 像这样:

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 { {1}},似乎路线无法识别{theme}与引擎中具有相同名称的内容相同。所以我现在使用查询字符串和cookie来控制主题,如下所示:

{theme}/{controller}/{action}/{id}

但这并不完美,我仍然需要帮助或自己找到方法。

1 个答案:

答案 0 :(得分:0)

如何使用区域来组织您的两个主题。您可以有两个区域:“黑色”和“白色”。他们每个人都有自己的控制器和动作。 路线模式为:{AreaName} / {Controller} / {Action} / {Id}。 检查此链接以了解如何使用区域。 http://www.codeguru.com/csharp/.net/net_asp/mvc/article.php/c20227/Using-Areas-in-ASPNET-MVC-Application.htm

相关问题