【问题标题】:Mvc area routing?mvc区域路由?
【发布时间】:2013-03-12 09:13:34
【问题描述】:

我的项目结构:

Controller
    AdminController
    HomeController

添加区域后我的项目结构我在项目中添加了一个管理区域,

Areas
    Admin
        Controller
            SomeController
Controller
    AdminController
    HomeController

然后所有链接都断开了。例如

@Html.ActionLink(
    "go to some action", 
    "SomeAction", 
    "Admin", 
    new { area = "" }, 
    null)

当我写上面的链接时,它会将我路由到www.myDomain.com/Admin/SomeAction,但这是区域操作,我想路由到 AdminController 操作。

我该怎么做?我应该更改区域或控制器名称吗?

更新

以上链接输出:

domain/Admin/SomeAction
// I expect that is AdminController/SomeAction
// but not. There is SomeAction in my admin controller
// I get this error "The resource cannot be found."
// because it looks my expected, but it works unexpected
// it tries to call AdminArea/SomeController/SomeAction

更新 2

例如:

 @Html.ActionLink(
    "go to some action", 
    "SomeAnotherAction", 
    "Admin", 
    new { area = "" }, 
    null)

对于上面的链接,我没有收到任何错误,因为我所在的区域有 SomeAnotherAction。

区域注册

public override void RegisterArea(AreaRegistrationContext context)
{
    context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { action = "Index", id = UrlParameter.Optional }
    );
}

谢谢...

【问题讨论】:

  • 您必须将其路由到其中包含 SomeAction 的控制器。现在,您正在从 AdminController 调用 SomeAction ActionResult。您想从 AreaController 调用 SomeAction。还是我错过了什么?
  • 已编辑。对我来说也很难解释。总结,我想调用项目主控制器动作,但它调用区域控制器动作。链接看起来正确,但工作不正常。

标签: asp.net-mvc routing area


【解决方案1】:

由于您首先注册了您的区域,因此它们具有优先权。解决这个问题没有简单的方法。最好的解决方案是将网站主要部分中的 AccountController 重命名为其他名称,以避免冲突。

另一种可能性是在您的区域路由注册中限制控制器:

context.MapRoute(
    "Admin_default",
    "Admin/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional },
    new { controller = "Some|SomeOther" }
);

现在只有对/Admin/Some/{action}/Admin/SomeOther/{action} 的请求会被路由到该区域,这意味着/Admin/SomeAction 将被全局路由定义拦截并路由到您的AdminController

【讨论】:

  • 第二种方式是可行的,但它不是优雅的方式,因为我应该所有区域控制器,对吧?如果是,我将更改我的管理员控制器名称...感谢您的建议...
猜你喜欢
  • 1970-01-01
  • 2011-08-07
  • 2012-08-30
  • 2010-12-09
  • 2018-05-31
  • 2011-03-17
  • 1970-01-01
  • 2020-07-12
相关资源
最近更新 更多