且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在MVC中将路由用于SEO友好URL

更新时间:2022-11-26 13:11:53

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

Since that's not a generic url but a concrete one (pointing to a product), you could use:

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添加到路由中,因为我认为这是错误的。如果确实需要,只需将其添加到路线中即可:

So, everything not matching to "Products" route will go to "Default". Note that I didn't add the ".aspx" to the rout since I believe it's a mistake. If you actually want it, just add it to the route:

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

此外,我建议使用以下更好的网址:

Also, I would suggest to use a better url with:

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