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

后端 未结 2 1433
心在旅途
心在旅途 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:22

    It seems that your scenario is covered fine by default route, so there is no need for a custom Stuff one.

    As to why the error is thrown, the fact that action is listed in defaults does not mean that it is actually becoming a part of a route. It should be mentioned in the route, otherwise it appears as there is no action at all. So what I think happens here is that first route is matched, but it cannot be processed as there is no action specified, so MVC passes request on to IIS, which throws the named error.

    The fix would be simple:

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

    But again, you shouldn't need that at all.

提交回复
热议问题