Routing by slug in asp.net mvc

自作多情 提交于 2019-12-11 03:15:32

问题


I have a controller action as you can see below:

public ActionResult Content(string slug)
{
    var content = contentRepository.GetBySlug(slug);

    return View(content);
}

I want this kind of urls to be routed to my action:

http://localhost/slug-of-my-content

Here is my RegisterRoutes method:

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

        routes.MapRoute(
           name: "GetContent",
           url: "{slug}",
           defaults: new { controller = "Page", action = "Content", slug = "" }
           );
    }

But it does not work, what am I doing wrong?

Thanks,


回答1:


1 put the slug route above default route,if not ,it never go the slug route
2 you slug can not be empty,if empty ,the url will be http://localhost/ it must go default route

routes.MapRoute(
name: "slug",
url: "{slug}",
defaults: new { controller = "Home", action = "show" },
constraints: new{ slug=".+"});

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

and i think don't pick "Content" as action name,becuse there is a Content Method in base class




回答2:


for dynamic routes, you could use:

routes.MapRoute(
    name: "PageName",
    url: "{pageName}",  
    defaults: new { controller = "Page", action = "Content", pageName = "defaultPage" }
);

which will map to ~/Pagename with the Action "Content" in the "Page" controller:

 public ActionResult Content(string pageName)
    {
        ViewBag.Message = pageName;
        return View();
    }


来源:https://stackoverflow.com/questions/31606522/routing-by-slug-in-asp-net-mvc

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