.NET MVC3路由 - 为什么这么混乱?

Ter*_*rry 1 url-routing asp.net-mvc-routing asp.net-mvc-3

我不知道为什么我经常与此斗争,但有人可以解释为什么这不起作用?

/重定向到控制器的index动作home.

/gallery/ 抛出404未找到的错误.

/gallery/index重定向到控制器的index动作gallery.

文档:

定义路径时,可以为参数指定默认值.如果URL中未包含该参数的值,则使用默认值.您可以通过将字典对象分配给Route类的Defaults属性来设置路由的默认值.

我不明白这是如何遵循这条规则的:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } 
        );
    }
Run Code Online (Sandbox Code Playgroud)

它对我来说:

  • 如果controller未定义a,请使用Home.
  • 如果action未定义,请使用Index.
  • 输入的URL包含一个控制器= gallery并且URL中不包含操作,因此它应该转到Index.

我是否遗漏了某些不必要的混淆和愚蠢的东西?

我总是发现MVC3路由有问题但接受了它.然后我开始使用Rails和Node框架,并且它们具有可笑的简单路由,所以现在.NET MVC只是在它不起作用时使我烦恼或者让我使用复杂的模式.

作为参考,以防有人询问,我的图库控制器,操作和视图都已定义并在我浏览时工作/gallery/index.

public class GalleryController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 5

你肯定应该做错事或有一些你没有告诉我们的代码.执行以下步骤:

  1. 使用默认向导(Internet应用程序)创建新的ASP.NET MVC 3应用程序
  2. 用以下内容替换内容HomeController.cs:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return Content("home/index");
        }
    }
    
    public class GalleryController : Controller
    {
        public ActionResult Index()
        {
            return Content("gallery/index");
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 击中 F5

这是发生的事情:

requested url    |   result
-----------------+---------------
/                |   home/index
/home            |   home/index
/home/           |   home/index
/home/index      |   home/index
/home/index/     |   home/index
/gallery         |   gallery/index
/gallery/        |   gallery/index
/gallery/index   |   gallery/index
/gallery/index/  |   gallery/index
Run Code Online (Sandbox Code Playgroud)

完全符合预期,不是吗?