.NET6 Areas Routing
ASP.NET Core Web API routing, Area Routing, 區域, 紀錄一下怕忘記。
參考文章
關鍵知識
依據幾篇文章閱讀,想要 routing 支援區域(area) 要用下面設定,如下:
app.MapControllerRoute("blog_route", "Blog/{controller}/{action}/{id?}",
defaults: new { area = "Blog" }, constraints: new { area = "Blog" });
app.MapControllerRoute("default_route", "{controller}/{action}/{id?}");
但經測試,Web API 專案預設的 MapControllers() 本身就已支援了,只差在區域(area)的宣示。
app.MapControllers(); // 本身就已支援區域(area)了,只差在區域(area)的宣示。
宣示區域(area)的方法也很簡單,在 Controller 掛上 AeraAttribute 並宣示區域名稱即可。如下例:
[Area("Blog")] // 宣示為 Area 並名為 "Blog"
[Route("api/[area]/[controller]")] // 這時 routing [area] 就有效果了。
[ApiController]
public class OrderController : ControllerBase
{
[HttpPost("[action]")]
public async Task<ActionResult<OrderModel>> SaveOrder(OrderModel formData)
{
...
}
[HttpPost("[action]/{id}")]
public async Task<ActionResult<OrderModel?>> GetOrder(string id)
{
...
}
}
沒圖沒真象
在方案總管的『Areas』目錄與其下的 Controllers 就依 MVC 的規則放入即可。

(EOF)
Last updated