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

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

本文介绍了如何在MVC中将路由用于SEO友好URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我们的global.asax文件中包含以下示例代码。因此,我的问题是我们如何拥有多个MapRoute以及如何使用它们????

Generally we have following sample code in our global.asax file. So, my question is how we can have multiple MapRoute and how to use them ???

我想要这样的URL:



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友善网址:

I want something like this, but i don't understand how to use this routing so that i can get SEO Friendly 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 }
            );
        }

预先感谢。

推荐答案

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

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

这篇关于如何在MVC中将路由用于SEO友好URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 20:11