Asp.Net: Removing the action name from the URL

爱⌒轻易说出口 提交于 2019-12-02 07:21:31

问题


I am trying to create a routing rule that allows me to use

http://localhost:*****/Profile/2

instead of

http://localhost:*****/Profile/Show/2

to access a page. I currently have a routing rule that successfully removes index when accessing a page. How do I apply the same concept to this?

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

回答1:


I have a couple of questions to clarify what you are trying to do. Because there could be some unintended consequences to creating a custom route.

1) Do you only want this route to apply to the Profile controller?

Try adding this route before the default route..

   routes.MapRoute(
        name: "Profile",
        url: "Profile/{id}",
        defaults: new { controller = "Profile", action = "Show" }

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

This new route completely gets rid of the Index and other actions in the Profile controller. The route also only applies to the Profile controller, so your other controllers will still work fine.

You can add a regular expression to the "id" definition so that this route only gets used if the id is a number as follows. This would allow you to use other actions in the Profile controller again as well.

   routes.MapRoute(
        name: "Profile",
        url: "Profile/{id}",
        defaults: new { controller = "Profile", action = "Show" }
        defaults: new { id= @"\d+" }
        );

Also, it would be a good idea to test various urls to see which route would be used for each of the urls. Go to NuGet and add the "routedebugger" package. You can get information on how to use it at http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx/



来源:https://stackoverflow.com/questions/33716438/asp-net-removing-the-action-name-from-the-url

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