如何在 MVC 中使用路由来实现 SEO 友好的 URL

2024-01-09

一般来说,我们的 global.asax 文件中有以下示例代码。所以,我的问题是我们如何拥有多个 MapRoute 以及如何使用它们???

我想要的网址如下:




http://domain/Home.aspx/Index/Cricket-Ball/12

  


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

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

我想要这样的东西,但我不明白如何使用这个路由,以便我可以获得 SEO 友好的 URL:




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

            routes.MapRoute(
                "Default1",
                "{controller}/{action}/{productname}/{id}",
                new { controller = "Home", action = "Index", productname = UrlParameter.Optional, id = UrlParameter.Optional }
            );

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

提前致谢。


由于这不是通用网址而是具体网址(指向产品),因此您可以使用:

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

        routes.MapRoute(
            "Products",
            "home/index/{productname}/{id}",
            new { controller = "Home", action = "Index" }
        );

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

因此,与“产品”路线不匹配的所有内容都将转到“默认”。请注意,我没有将“.aspx”添加到路由中,因为我认为这是一个错误。如果您确实需要它,只需将其添加到路线中即可:

routes.MapRoute(
            "Products",
            "home/index.aspx/{productname}/{id}",
            new { controller = "Home", action = "Index" }
        );

另外,我建议使用更好的网址:

routes.MapRoute(
            "Products",
            "products/{productname}/{id}",
            new { controller = "Home", action = "Index" }
        );
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 MVC 中使用路由来实现 SEO 友好的 URL 的相关文章

随机推荐