Dynamic routing action name in ASP.NET MVC

爷,独闯天下 提交于 2019-11-29 08:55:21
Nkosi

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