MVC Routing with no (or a default) action name

。_饼干妹妹 提交于 2020-01-25 09:52:10

问题


Using MVC 5, I am trying to get some friendly controller/action names working through routing. Banging my head against the wall with this.

Given this controller:

MyController
    Index(startPage, pageSize)
    EditAction(itemId)

I am using two routes (defined under an inherited AreaRegistration class)

context.MapRoute(
            "MyControllerRoute",
            "myArea/MyController/{action}/{itemId}",
            new
            {
                controller = "MyController",
                action = "Index",
                itemId = UrlParameter.Optional
            },
            new[] {"MySite.Areas.MyArea.Controllers"});

context.MapRoute(
            "MyControllerRoutePaged",
            "myArea/MyController/{action}/{startPage}/{pageSize}",
            new
            {
                controller = "MyController",
                action = "Index",
                pageSize = UrlParameter.Optional,
                startPage = UrlParameter.Optional
            },
              new[] {"MySite.Areas.MyArea.Controllers"});

I'd like to achieve these links:

mysite.com/MyArea/MyController/startPage/pageSize
mysite.com/MyArea/MyController/EditAction/itemId

mysite.com/MyArea/MyController2/ (this being the Index action for a given controller)
mysite.com/MyArea/MyController3/ (this being the Index action for another controller)


mysite.com/MyArea/MyController/ (mysite.com/MyArea/MyController/0/20 would also work if paging existis on the controller)
mysite.com/MyArea/MyController/5/20
mysite.com/MyArea/MyController/EditAction/5

The paging links appear on the default Index page. Not on any "action pages". In particular I am looking to hide the Index action name, so I don't end up with links like:

mysite.com/MyArea/MyController/MyController/.../

I can achieve this if I drop the {action} placeholder in the routes but the routes end up clashing. I have tried using ActionLink and RouteLink (defining the route name) but there's always one route that matches first and breaks the next one. If I change the ordering of the routes this still happens but the other way around.

I am using a route debugger and I can see where things are failing but I keep going around in circles trying to get it working.

Any ideas? Thanks.


回答1:


I think you should use Attribute Routing for custom routes.



来源:https://stackoverflow.com/questions/59142928/mvc-routing-with-no-or-a-default-action-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!