2013-11-22 139 views
0

我只啓用默認路由:ASP.NET MVC路線

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

這將resove像路徑:主機名/首頁/指數,主機名/主頁/美孚,主機名/主頁/酒吧/ 23就好了。
但我還必須啓用這樣的路線:主機名/ {ID}這應該指向 到:
控制器:首頁
操作:指數
(編號): Index操作參數 「ID」

這樣的路線甚至可能嗎?

回答

1

未測試: 你的默認路由

+0

這只是殺死了所有我的AJAX調用:) – dakt

+0

什麼網址üR IN ajax請求? –

+0

我有幾個人:/首頁/註冊/ {帕拉姆},/首頁/登錄/ {參數}等 – dakt

1

如果id是一個數字,你可以添加一個路線上述另一個並定義一個正則表達式約束下創建這樣

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

路線:

routes.MapRoute(
    name: "IdOnlyRoute", 
    url: "{id}", 
    defaults: new { controller = "Home", action = "Index" }, 
    constraints: new { id = "^[0-9]+$" } 
); 
+0

不,這是一個字符串:) – dakt

+0

如果它是一個字符串有一些特定的約束,你仍然可以使用上面的解決方案...如果它只是一個字符串像其他任何東西然後你可能不走運。 – Tallmaris

0

由於時間不夠,我配置了路由fo每一個行動。幸運的是,它們並不多。 :)

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

     routes.MapRoute(
      name: "IndexWithOutParam", 
      url: "", 
      defaults: new { controller = "Home", action = "Index" } 
     ); 

     routes.MapRoute(
      name: "Login", 
      url: "Home/Login", 
      defaults: new { controller = "Home", action = "Login" } 
     ); 

因此,最後的路線重複了其他行動。不知道它是否可以做得更好,但它的工作原理。

0

您是否嘗試過使用AttributeRouting包裝?

然後你的代碼看起來像這樣

[GET("/{id}", IsAbsoluteUrl = true)] 
    public ActionResult Index(string id) { /* ... */ }