首页 > 解决方案 > 将文件夹添加到 ASP.net MVC 5 站点中的所有 URL

问题描述

我有一个具有这种结构的 MVC 5 站点:

example.com
example.com/area1 (index for whole section)
example.com/area2/item5 (specific item for section)

出于 SEO 原因,我想将每个 URL 更改为:

example.com/keyword (redirected from example.com)
example.com/keyword/area1
example.com/keyword/area2/item5

关键字是固定的并且总是相同的,尽管在未来的某个时候可能会有一个结构相同但内容不同的网站使用不同的关键字。但这可能至少要几个月的时间。

什么是实现上述最快/最简单的方法。能够获得关键字的名称将是以后的优势,但现在不是必需的。

我可以使用属性路由,尽管我必须更新很多 ActionMethods 才能做到这一点——而且目前大多数甚至不使用属性路由。

谢谢。

更新

我尝试将以下内容添加到 RouteConfig.cs,但由于某种原因,Url 没有任何工作:

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

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

解决方案


public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    string  keyword = "keyword";
    // keyword route - it will be used as a route of the first priority 
    routes.MapRoute(
        name: "Defaultkeyword",
        url: "{keyword}/{controller}/{action}/{id}",
        defaults: new
        {
            controller = "Home",
            action = "Index",
            id = UrlParameter.Optional,
            keyword = keyword
        });

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

您还需要将此 Defaultkeyword 路由添加到您的 Area1AreaRegistration.cs 文件中

public override void RegisterArea(AreaRegistrationContext context)
 {
     context.MapRoute(
            "Area1_defaultKeyword",
            "{Keyword}/Area1/{controller}/{action}/{id}",
            new { Keyword = "Keyword", controller = "HomeArea1", action = "Index", id = UrlParameter.Optional }
            );

 context.MapRoute(
            "Area1_default",
            "Area1/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
           );
 }

推荐阅读