0

我有一个带有公司区域的 MVC4 应用程序。

给定文件结构:

Areas   
\
  Companies
    \
     Controllers
       |
       DefaultController (Contains Index and Edit actions)
       TestController (Contains Index and Test action)

我希望我的 URL 是这样的:

  • /公司
  • /公司/编辑
  • /公司/测试
  • /公司/测试/测试

我的路线设置就像在我的 CompaniesAreaRegistration 课程中一样。

context.MapRoute(
    name: "Companies_default",
    url: "Companies/{controller}/{action}/{id}",
    defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
            );

结果:

  • /公司 - 作品
  • /公司/编辑 - 404
  • /公司/默认/编辑 - 作品
  • /公司/测试 - 作品
  • /公司/测试/测试 - 作品

如何在 URL 中没有“默认”的情况下访问我的 DefaultController.Edit() 操作?

更新

根据布拉德的回答,我知道我可以像这样对路径进行硬编码,它会起作用。我真的希望有更多的自动解决方案。我不知道我最终会对某些区域的默认控制器执行多少操作。我不想为每个人创建一条新路线。

这是在 App_Start/RouteConfig.cs 文件中作为 MVC 模板的一部分添加的默认路由。

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

如果我在 HomeController 上有一个名为“Test”的操作,我可以使用 URL /Test 执行该操作。我不必添加带有“/Test/{id}”之类的 URL 的新路由即可使其正常工作。它似乎忽略了 URL 的 {controller} 部分并使用默认控制器配置。

当您在区域中执行此操作时,为什么此行为会发生变化?

Area 路由与 Default 路由完全相同,除了 URL 的“Companies/”前缀。

作为测试,我将我的默认路由 URL 更改为url: "Example/{controller}/{action}/{id}",我仍然可以通过 URL /Example/Test 访问 HomeController.Test()。

4

1 回答 1

2

使用:

context.MapRoute(
    name: "Companies_Edit",
    url: "Companies/Edit/{id}",
    defaults: new { controller = "Default", action = "Edit", id = UrlParameter.Optional }
);

记住参数是从左到右填充的(不能跳过{controller},只能填充{action}。如果要{controller}假设,请在 中指定defaults

于 2013-04-07T00:32:20.087 回答