[英]Questions about routing in Asp.net Core MVC 2
我無法確定asp.net核心MVC 2中的路由機制。
這是我所擁有的:
我已經建立了一個功能頁面,將“材料”添加到“應用程序”中。
調用此頁面的URL是:
http:// localhost:33333 / AddMaterial / Index / 57
使用默認路由:
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}"
);
其中57是應用程序ID,因此我知道什么“應用程序”獲得了新的“材料”。 控制器中的Index Method看起來像這樣,並按預期工作:
[HttpGet] public IActionResult Index(string id)
{
var model = GetModel(context, int.Parse(id));
return View("Index", model);
}
到目前為止一切順利... 現在這是我的問題:
我想使用相同的控制器並查看還可以編輯“材料”。 但是為此,我需要在Index()中使用兩個參數。 我需要:
string applicationId
string materialId
作為參數。
所以我添加了一條新路線:
routes.MapRoute(
name: "whatImTryingToAchieve",
template: "{controller}/{action}/{applicationId?}/{materialId?}"
);
當然,我更新了控制器:
public IActionResult Index(string applicationiId, string materialId)
{
// Do stuff with materialId etc.
// ...
return View("Index", model);
}
我知道路由系統有特定的順序。 因此,我嘗試在默認路由之前定義新路由。 那沒用。 然后,我嘗試將其放置在默認路由之后,該路由也不起作用。
我通讀了很多有關路由系統的信息,但似乎找不到我的簡單問題的答案:
如何添加其他特定路線?
幫助將不勝感激:)
編輯:IgorsŠutovs建議的基於屬性的路由
控制器:
[Authorize(Roles = "Admins")]
[Route("AddMaterial")]
public class AddMaterialController : Controller
{
//....
[Route("AddMaterial/{applicationId}/{otherid}")] // Nope. Nothing.
[HttpGet] public IActionResult Index(string applicationId, string otherid)
{
return View();
}
[Route("AddMaterial/Index/{applicationId}")] // Didn't work.
[Route("AddMaterial/{applicationId}")] // Didn't work either...
[HttpGet] public IActionResult Index(string applicationId)
{
return View();
}
}
屬性庫路由就這么多。
我將對所描述問題的本質提供主觀意見。 似乎可以將問題改寫為:“使用ASP.NET Core設計路線並使用多個參數解決此類情況的正確方法是什么?”
TLDR:使用基於屬性的路由
這是ASP.MVC 5中添加的新型路由。從那時起,舊的路由機制就被視為“基於常規的”。 ASP.NET Core當前允許兩者混合使用。 我將提供一個詳細的示例,說明如何使用基於屬性的路由解決上述問題,因為新方法具有以下優點:
繼續解決方案。 假設我們有2個模型:應用程序和材料。 我將創建2個不同的控制器來管理每個控制器。 從您的示例中,我了解到這些域實體之間的關系是一對多的,例如,一個應用程序可能具有許多材料。 這建議以下路線:
GET: applications/{applicationId}
GET: applications/{applicationId}/materials/{materialId}
……回顧一下路由的原理。
然后,ApplicationController將如下所示:
[Route("applications")]
public class ApplicationController
{
[HttpGet("{applicationId}")]
public IActionResult Index(string applicationId)
{
// return your view
}
}
雖然MaterialController看起來像這樣:
[Route("applications/{applicationId}/materials")]
public class MaterialController
{
[HttpGet("{materialId}")]
public IActionResult Index(string applicationId, string materialId)
{
// return your view
}
}
現在可以將Startup.cs的Configure方法中對UseMvc(..)擴展方法的調用簡化為:
app.UseMvc();
希望您會發現它有用!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.