1

我不知道为什么我一直在为此苦苦挣扎,但是有人可以解释为什么这不起作用吗?

/重定向到控制器的index操作。home

/gallery/抛出 404 not found 错误。

/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 } 
        );
    }

对我来说,它是这样写的:

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

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

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

以供参考,以防有人问起,当我浏览到/gallery/index.

public class GalleryController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}
4

2 回答 2

5

You definitively oughta be doing something wrong or there is some code you haven't shown us. Perform the following steps:

  1. Create a new ASP.NET MVC 3 application using the default wizard (Internet Application)
  2. Replace the contents of HomeController.cs with this:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return Content("home/index");
        }
    }
    
    public class GalleryController : Controller
    {
        public ActionResult Index()
        {
            return Content("gallery/index");
        }
    }
    
  3. Hit F5

Here's what happens:

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

Exactly as expected, isn't it?

于 2012-07-09T21:19:07.923 回答
1

问题是我有一个隐藏目录(未包含在我的解决方案中)与我的错误路线同名:/gallery.

幸运的是,今天早上我太累了,无法打我的显示器。

感谢大家的建议,所有 +1 的有用指导。

PS。为了帮助我调查问题,我使用了Phil Haack 的路由调试器

于 2012-07-10T14:17:05.147 回答