ASP.NET MVC路由:如何省略" index"来自一个URL

时间:2015-08-21 11:21:32

标签: c# asp.net asp.net-mvc asp.net-mvc-5 asp.net-mvc-routing

我有一个名为" StuffController"使用无参数索引操作。我希望通过mysite.com/stuff

形式的网址调用此操作

我的控制器定义为

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服务器配置为不列出此目录的内容。

网址mysite.com/stuff/index运行正常。我做错了什么?

2 个答案:

答案 0 :(得分:4)

  

HTTP错误403.14 - 禁止将Web服务器配置为不列出此目录的内容。

该错误表示您的项目中有一个名为/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 }
    );
}

答案 1 :(得分:1)

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

至于为什么抛出错误,动作在默认情况下列出的事实并不意味着它实际上正在成为路径的一部分。它应该在路线中提及,否则看起来根本就没有动作。所以我认为这里发生的是第一个路由是匹配的,但由于没有指定动作而无法处理,因此MVC将请求传递给IIS,这会引发命名错误。

修复很简单:

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

但同样,你根本不应该那样。