【问题标题】:Bind route to custom physical path in mvc4将路由绑定到 mvc4 中的自定义物理路径
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 谢谢郭君,但是这个我恐怕不能使用区域,因为如果我想同时使用“主题”和“区域”,那将是一个又出问题了。
    猜你喜欢
    • 2014-03-30
    • 2013-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 2019-07-02
    • 1970-01-01
    相关资源
    最近更新 更多