【问题标题】:Routing by slug in asp.net mvc在 asp.net mvc 中通过 slug 进行路由
【发布时间】:2015-07-24 09:10:11
【问题描述】:

我有一个控制器动作,如下所示:

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

    return View(content);
}

我希望将此类 url 路由到我的操作:

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

这是我的 RegisterRoutes 方法:

    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 = "" }
           );
    }

但它不起作用,我做错了什么?

谢谢,

【问题讨论】:

  • 您好,我也有同样的问题。你能在控制器部分提供一点帮助吗?谢谢

标签: asp.net-mvc routing asp.net-mvc-routing


【解决方案1】:

1 将 slug 路由放在默认路由之上,如果没有,它永远不会走 slug 路由
2 你的slug不能为空,如果为空则url为http://localhost/必须走默认路由

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 });

我认为不要选择“内容”作为动作名称,因为基类中有一个内容方法

【讨论】:

    【解决方案2】:

    对于动态路由,您可以使用:

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

    这将映射到 ~/Pagename 与“页面”控制器中的操作“内容”:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-02
      • 2011-06-08
      • 2016-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多