ASP.NET MVC 路由:如何从 URL 中省略 "index"

ASP.NET MVC Routes: How do I omit "index" from a URL

我有一个名为 "StuffController" 的控制器,它具有无参数索引操作。我希望以 mysite.com/stuff

的形式从 URL 调用此操作

我的控制器定义为

public class StuffController : BaseController
{
    public ActionResult Index()
    {
        // Return list of Stuff
    }
}

我添加了自定义路由,因此路由定义如下:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    // Custom route to show index
    routes.MapRoute(
        name: "StuffList",
        url: "Stuff",
        defaults: new { controller = "Stuff", action = "Index" }
    );


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

}

但是当我尝试浏览 mysite.com/stuff 时出现错误

HTTP 错误 403.14 - 禁止

Web 服务器配置为不列出此目录的内容。

URL mysite.com/stuff/index 工作正常。我做错了什么?

默认路由似乎可以很好地覆盖您的方案,因此不需要自定义 Stuff

至于为什么会报错,action列在defaults中并不代表它真的成为了route的一部分。应该在路由中提及,否则看起来根本没有任何动作。所以我认为这里发生的是第一条路由匹配,但由于没有指定操作而无法处理,因此 MVC 将请求传递给 IIS,IIS 抛出命名错误。

修复很简单:

// Custom route to show index
routes.MapRoute(
    name: "StuffList",
    url: "Stuff/{action}",
    defaults: new { controller = "Stuff", action = "Index" }
);

但同样,您根本不需要它。

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.

该错误表明您的项目中有一个名为 /Stuff 的虚拟目录(可能是物理目录)。默认情况下,IIS 将首先到达此目录并查找默认页面(例如 /index.html),如果不存在默认页面,将尝试列出目录的内容(这需要配置设置)。

这一切都发生在 IIS 将调用传递给 .NET 路由之前,因此具有名称 /Stuff 的目录会导致您的应用程序无法正常运行。您需要删除名为 /Stuff 的目录或为您的路由使用不同的名称。

正如其他人所提到的,默认路由涵盖了这种情况,因此在这种情况下不需要自定义路由。

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    // Passing the URL `/Stuff` will match this route and cause it
    // to look for a controller named `StuffController` with action named `Index`.
    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}