Dynamic routing action name in ASP.NET MVC

前端 未结 1 835
深忆病人
深忆病人 2020-12-18 13:20

I would like to create a dynamic routing to a URL like following:

http://localhost:51577/Item/AnyActionName/Id

Please note that the control

相关标签:
1条回答
  • 2020-12-18 13:51

    What you are referring to in your question is called a slug.

    I answered a similar question here for web api

    Web api - how to route using slugs?

    With the slug at the end the route config would look like this

    public static void RegisterRoutes(RouteCollection routes) {
    
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
        routes.MapRoute(
            name: "Items",
            url: "Item/{id}/{*slug}",
            defaults: new { controller = "Item", action = "Index", slug = RouteParameter.Optional }
        );
    
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    
    }
    

    which could match an example controller action...

    public class ItemController : Controller {
        public ActionResult Index(int id, string slug = null) {
            //...
        }
    }
    

    the example URL...

    "Item/31223512/Any-Item-Name"
    

    would then have the parameters matched as follows...

    • id = 31223512
    • slug = "Any-Item-Name"

    And because the slug is optional, the above URL will still be matched to

    "Item/31223512"
    
    0 讨论(0)
提交回复
热议问题