针对“更漂亮的URL”的MVC4 URL重写别名

时间:2013-02-09 00:36:49

标签: iis razor asp.net-mvc-4 asp.net-mvc-routing url-rewrite-module

我目前对微软的MVC4有点新,我不太了解路由以及我想要的。

我想要做的是让我的网址更具人性化。目前我的网址看起来像这样:

  • foo.com/UserProfile/Details/6
  • foo.com/UserExperience/Details /
  • foo.com/UserSpecificController/Edit/8

所有用户控制器都以“用户”为前缀我想知道是否可以更改这些网址,使它们看起来像这样:

  • foo.com/u/Profile/Details/6
  • foo.com/u/Experience/Details /
  • foo.com/u/SpecificController/Edit/8

我的第一次尝试是使用IIS:

<rewrite>
        <rules>
            <rule name="AddTrailingSlashRule1" stopProcessing="true">
                <match url="(.*[^/])$" />
                <conditions>
                    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                </conditions>
                <action type="Redirect" url="{R:1}/" />
            </rule>
            <rule name="Pretty User Redirect" enabled="false" stopProcessing="true">
                <match url="User(.*)/(.*)" />
                <action type="Redirect" url="u/{R:1}/{R:2}" />
                <conditions>
                </conditions>
            </rule>
            <rule name="User pretty URL Rewrite">
                <match url="u/(.*)/(.*)" />
                <action type="Rewrite" url="User{R:1}/{R:2}" />
            </rule>
        </rules>
    </rewrite>

除非我得到/你/我所有的链接,无处不在......

例如: foo.com/Home/WhatWeDo /

会像: foo.com/u/Home/WhatWeDo /

这将是404.

我正在使用默认路由配置

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

我的所有链接都是使用@ Html.ActionLink(...)

绘制的

如果有人能够对此有所了解,那将非常感激。

1 个答案:

答案 0 :(得分:0)

删除自定义IIS重写规则并将其插入默认路由

之前
routes.MapRoute(
    name: "UserProfile",
    url: "u/Profile/{action}/{id}",
    defaults: new { controller = "Home", id = UrlParameter.Optional }
);

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

编辑:区域

使用区域对相关控制器进行分组

Profile controller within a User area
/User/Profile/Details

Experience controller
/User/Experience/Details

然后只有一个自定义规则用于该区域的RegisterArea来替换路线中的“u”

context.MapRoute(
    "UsersRoute",
    "u/{controller}/{action}/{id}",
    new { Controller = "Home", action = "Index", id = UrlParameter.Optional },
    new string[] { "MyNamespace.MyProj.Areas.User.Controllers" }
);