2015-06-21 48 views
2

我需要幫助創建一個像MVC網站中的URL路由一樣的永久鏈接。ASP .NET MVC,像路由配置一樣創建永久鏈接

蛞蝓已經被設置爲www.xyz.com/profile/{slug}:代碼:

routes.MapRoute(
    name: "Profile", 
    url: "profile/{slug}", 
    defaults: new { controller = "ctrlName", action = "actionName" } 
      ); 

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

什麼,我需要做到的是,你WordPress的永久鏈接或一把umbraco看到一個網址固定鏈接。我需要有www.xyz.com/{Slug}。

我曾嘗試使用:

routes.MapRoute(
    name: "Profile", 
    url: "{slug}", 
    defaults: new { controller = "ctrlName", action = "actionName" } 
      ); 

但是,這並沒有爲我工作。

編輯:

如果我切換上面的路線CONFIGS中,嵌入功能的作品,但在常規路由不再一樣。

這是否意味着我被迫在所有頁面上實現永久鏈接功能?

+0

您是否有一個名爲「ctrlName」的控制器,名爲「actionName」的操作方法?如果是,則操作應該有一個名爲「slug」的字符串參數。如果否,請在路由配置中設置正確的控制器和操作名稱。 –

+0

我把ctrlName和actionName設置爲slug作爲字符串參數。就像我說的/ profile/{Slug}正在工作。但/ {Slug}不是。/{Slug}用於相同的ctrlName actionName。 –

+0

順便說一下,例外情況是:HTTP 404.您正在查找的資源(或其某個依賴項)可能已被刪除,名稱已更改或暫時不可用。 –

回答

2

如果你想從根目錄(site.com/{slug)獲得永久鏈接,那麼你可以使用你的slug路由。 但是對於任何其他控制器/操作的工作,您需要明確指定一個路徑,以便在您的slu route路線上方。例如:

routes.MapRoute(
    name: "Services", 
    url: "Services/{permalink}/", 
    defaults: new { controller = "Page", action = "Services"} 
); 
routes.MapRoute(
    name: "Requests", 
    url: "Requests/{action}/{id}", 
    defaults: new { controller = "Requests", action = "Index", area = "" }, 
    namespaces: new String() {"ProjectNamespace.Controllers"} 
); 
routes.MapRoute(
    name: "AdminPreferences", 
    url: "Admin/Preferences", 
    defaults: new { controller = "Preferences", action = "Index", area = "Admin"}, 
    namespaces: new String() {"ProjectNamespace.Areas.Admin.Controllers"} 
); 
... 
routes.MapRoute(
    name: "Profile", 
    url: "{slug}", 
    defaults: new { controller = "ctrlName", action = "actionName" } 
); 

這應該工作;我已經完成了這個之前,但恐怕我從內存和VB回答。我在這個文本編輯器中將代碼從VB轉換爲C#,所以我不能確定沒有錯誤。

+0

謝謝你的回答,我已經解決了這個問題,但是你的答案應該可以工作。 –