Asp.net-Mvc-4

將 Url.RouteUrl() 與區域中的路線名稱一起使用

  • March 27, 2019

作為旁注,我了解整個模棱兩可的控制器名稱問題,並使用命名空間來使我的路由正常工作,所以我認為這不是問題。

到目前為止,我有我的項目級控制器,然後是具有以下註冊的使用者區:

public class UserAreaRegistration : AreaRegistration
{
   public override string AreaName
   {
       get
       {
           return "User";
       }
   }

   public override void RegisterArea(AreaRegistrationContext context)
   {
       context.MapRoute(
           "UserHome",
           "User/{id}",
           new { action = "Index", controller = "Home", id = 0 },
           new { controller = @"Home", id = @"\d+" }
       );

       context.MapRoute(
           "UserDefault",
           "User/{controller}/{action}/{id}",
           new { action = "Index", id = UrlParameter.Optional }
       );
   }
}

“UserHome”路線在那裡,所以我可以允許路線/User/5/User/Home/Index/5看起來更清潔的 IMO。

理想情況下,我想使用Url.RouteUrl("UserHome", new { id = 5 }), 在其他地方生成路線,但這總是返回空白或給我一個異常,說它找不到路線名稱,這顯然是存在的。

但是,當我使用它時,Url.RouteUrl("UserHome", new { controller = "Home", action = "Index", id = 5 })它沒有問題。

當路由映射中已經有預設值時,為什麼我必須指定動作和控制器?我錯過了什麼?

大家請看下面@ryanulit 的回答。使用較新的框架版本可能會為您解決此問題。

不確定是否有熱修復,但現在的行為有點不同。使用您的確切程式碼並嘗試:

Url.RouteUrl("UserHome", new { id = 5 })

我現在得到:

/User/5?httproute=True 

這看起來仍然很尷尬,所以我嘗試了路由並添加了另一個預設參數:

context.MapRoute(
           "UserHome",
           "User/{id}",
           new { action = "Index", controller = "Home", area = "User", id = 0, 
                      httproute = true },
           new { controller = @"Home", id = @"\d+" }
       );

現在當我使用

Url.RouteUrl("UserHome", new { id = 5 })

我得到一個不錯的網址

/User/5

免責聲明httproute=true在路由聲明中可能會有不想要的副作用。

此外,更詳細的用法:

@Url.RouteUrl("UserHome", new { controller = "Home", action = "Index", id = 5 })

仍然有效。

嘗試這個:

@Url.Action("Index", "Home", new { Area = "User" })

引用自:https://stackoverflow.com/questions/17734684