2013-03-24 168 views
2

我目前正試圖弄清楚如何更改我的博客的url規則。ASP.Net MVC4自定義路由

現在的網址是/ Blog/Details/1,但我讀到這是一個更好的SEO做法,使網址/Blog/Details/Post-Title。我在標記爲FriendlyUrl的博客數據庫中創建了一個額外的字段,並且在創建博客條目時,我將空格替換爲破折號( - ),但現在我不知道如何使我的應用程序正常工作。

有人告訴我看看我的global.asx.cs,但這是我的樣子。

public class MvcApplication : HttpApplication 
{ 
    protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 

     WebApiConfig.Register(GlobalConfiguration.Configuration); 
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 
     AuthConfig.RegisterAuth(); 
    } 
} 

下面是詳細信息

public ActionResult Details(int id = 0) 
    { 
     Blog blog = _db.Blogs.Find(id); 
     if (blog == null) 
     { 
      return HttpNotFound(); 
     } 
     return View(blog); 
    } 

,這裏是目前正在使用鏈接到博客條目的鏈接我的控制器代碼。

<a href="@Url.Action("Details", "Blog", new { id=item.Id})">@Html.DisplayFor(modelItem => item.Title)</a> 

在此先感謝您的幫助。

回答

5

在app_start routing.cs首先將這個路由文件:

 routes.MapRoute(
      "Blog", 
      "Blog/{id}", 
      new { controller = "Details", action = "Blog", id=0 } 
     ); 

只要路由引擎找到這條路首先,在博客開頭的路線/將被路由到位指示Details和行動Blog


如果您希望專注於一個搜索引擎友好的塞更具描述性的路線,使用這條路線:

 routes.MapRoute(
      "Blog", 
      "Blog/{postid}/{slug}", 
      new { controller = "Details", action = "Blog", id=0, slug="" } 
     ); 

與博客/ {帖子ID}開頭的路線將被路由到位指示Details和行動Blog。當您的操作或操作過濾器看到一條將slug留空的路由時,請在數據庫中查找並將您的用戶重定向到該URL。

所以,如果,例如,你得到像

/Blog/1287 

的路線,你應該將用戶重定向到

/Blog/1287/how-to-fix-your-routing-engine 

這種架構非常類似於這樣使用的設計。注意,如果你試圖去

/questions/15593545/ 

你會發現自己在

/questions/15593545/asp-net-mvc4-custom-routing 

動作方法現在看起來像這樣

public ActionResult Blog (int postid, string slug) 
{ 
+0

偉大的東西會發生什麼,謝謝先生。 – 2013-03-24 00:23:16

+1

很高興幫助... – 2013-03-24 00:24:41

+0

你可以擴展一點我應該如何修改我的控制器和實際的鏈接。我所遇到的問題如上所述正常工作。再次感謝 – 2013-03-24 00:50:50