使用“/Index”阻止访问路由

Prevent access to route with "/Index"

在 .NET MVC 路由中,有没有一种方法可以让我在显式键入时阻止访问 Index 操作,即我希望它成为 return 404,就好像该操作无效一样?

我想达到:

www.example.com /Index => 404 error code

www.example.com => "Root", should run the Index action on the default controller.

就像 Whosebug 上的类似,/Index 给了我 404,这也是我想要模拟的。

现在,//Index 都为我提供了一个有效页面 - 起始页。

当前默认路线:

routes.MapRoute(
                "Default",                                              // Route name
                "{controller}/{action}/{id}",                           // URL with parameters
                new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
            );

假设您的意思是 /Home/Index 而不是 /Index,您只需将 IgnoreRoute 添加到您的配置中。

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

        routes.IgnoreRoute("Home/Index");
        routes.IgnoreRoute("Home");

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

我通过将默认路由 (Root) 的 URL 更改为空来解决它。

In ASP.NET Core 1.1.1:

app.UseMvc(routes =>
{
   routes.MapRoute("Home_Root", "", new { controller = "Home", action = "Index" });
});