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

后端 未结 2 1471
心在旅途
心在旅途 2021-01-27 04:48

I have a controller called \"StuffController\" with a parameterless Index action. I want this action to be called from a URL in the form mysite.com/stuff

My

2条回答
  •  渐次进展
    2021-01-27 05:17

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

    The error indicates that you have a virtual directory (probably a physical one) in your project called /Stuff. By default, IIS will first reach this directory and look for a default page (for example /index.html), and if no default page exists will attempt to list the contents of the directory (which requires a configuration setting).

    This all happens before IIS passes the call to .NET routing, so having a directory with the name /Stuff is causing your application not to function correctly. You need to either delete the directory named /Stuff or use a different name for your route.

    And as others have mentioned, the default route covers this scenario so there is no need for a custom route in this case.

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

提交回复
热议问题