【问题标题】:MVC3 Routing with Areas带区域的 MVC3 路由
【发布时间】:2012-02-17 07:43:36
【问题描述】:

我有一个包含两个区域和一个根区域的 MVC3 应用程序。一般结构看起来像 根

- Root/Areas/Manager
    * Views/Home/Index.cshtml
    * ManagerAreaRegistration.cs
- Root/Areas/Participant
    * Views/Home/Index.cshtml
    * ParticipantAreaRegistraion.cs
- Root
    * Views/Home/Index.cshtml
    * Views/Account/Register.cshtml
    * Global.asax.cs

我有两个路由问题。首先是我无法导航到 Root/Views 文件夹中的任何页面,除了 Global.asax.cs 文件中设置为默认的页面。 Global.asax.cs 文件如下所示:

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
   "Default", // Route name
   "{controller}/{action}/{id}", // URL with parameters
   new {controller="Home" , action = "Index", id = UrlParameter.Optional }, 
   new[] { "MVCApplication.Controllers" }    // for areas 
   );
...     
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
...

作为起始页的 Root/Views/Home/Index.cshtml 中的代码如下所示:

@Html.ActionLink("Accounts","Register", new {area="", controller="Accounts"},null)
@Html.ActionLink("Manager", "Index", new { area = "Manager", controller = "Home" })
@Html.ActionLink("Participant", "Index", new { area = "Participant", controller = "Home" })

这两个区域链接工作正常,因为我已将路由添加到每个区域的注册文件中,但是到根中的另一个页面 Accounts/Register 的链接给出了“找不到资源错误”。但是,如果我将 Global.asax.cs 路由更改为具有

    new {controller="Accounts" , action = "Register", id = UrlParameter.Optional }, 

在默认路由中,然后我可以从注册页面开始。

所以我的第一个问题是:我如何使用路由来访问区域和根中的两个页面(即帐户/注册页面)?

我的第二个问题与这些领域本身有关。因为他们都有一个“家庭”控制器,我把区域名称放在一个前面来区分它,但我不想这样做。目前'ParticipantAreaRegistration.cs 文件有代码:

  context.MapRoute(
            "Participant_default",
            "Participant/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional },
          new[] { "MvcApplication.Areas.Participant.Controllers"  }    // for areas 
            );

给出“localhost**/Participant/Home”的 URL

而 ManagerAreaRegistraion.cs 有代码

 context.MapRoute(
            "Manager_default",
            "{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional },
                         new[] { "MvcApplication.Areas.Manager.Controllers" }    // for areas 

        );

给出“localhost***/Home/”的 URL

我的第二个问题是:我怎样才能为经理和参与者(或任意数量的区域)提供“localhost**/Home”的 URL,而不必显示区域名称网址?

我知道这个问题与其他已经记录在案的问题类似,但我已经搜索了这些都无济于事,并且目前效率低下,所以我想我会尝试具体询问。谢谢。

【问题讨论】:

    标签: asp.net-mvc-3 url-routing asp.net-mvc-3-areas


    【解决方案1】:

    您可以使用自定义路由。

    类似的东西:

    MVC 2 AreaRegistration Routes Order

    使用上述问题中的解决方案,可以编写自定义的路由顺序。

    在我的一个应用程序中,我有名为 Admin、Blog、Members 和 民众。我已将公共区域路由为 url: http://localhost:4000/,管理员为:http://localhost:4000/admin,博客 如:http://localhost:4000/blog等。如果你想要我的代码,我可以给 你。

    【讨论】:

    • 感谢您的回复。我知道它应该有效,但我还没有成功。如果您不介意共享您的代码,那可能会有所帮助。如果您可以将其压缩并发送.. 或者只是将相关的 sn-ps 放入电子邮件中,那会很酷。 (gmail 的 aespaldi)。
    猜你喜欢
    • 2012-02-19
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多