0

我目前對微軟的MVC4有點新,我不太瞭解路由以及我想要的。MVC4 URL改寫爲「漂亮的URL」的別名

我想要做的是讓我的網址更具人性化可讀性。目前,我有看起來像這樣的網址:

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

所有用戶控制器的前綴爲「用戶」我在想,如果有可能改變這些網址,讓他們看起來像這樣:

  • foo.com/ U /資料/細節/ 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> 

這工作得很好,除了我會得到/ U /我所有的環節,無處不在的......

例如: 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(...)

如果任何人都可以闡明這一點,那將不勝感激。

回答

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

這似乎有點優雅,我必須爲我的每個控制器做到這一點? 有沒有辦法添加我自己的代碼/模塊,將重寫URL我想要的? – William 2013-02-09 05:15:30

+0

也許你想在你的項目領域。然後,您將更改控制器類名稱,而不必擔心自定義路由/重寫。 – Jasen 2013-02-09 20:49:36