如何定义到多个区域的端点路由 [英] How to define an endpoint route to multiple areas
问题描述
我正在尝试定义一个路由到多个区域的MapAreaControllerRoute()
.但是,在ASP.NET Core 3.0中,需要设置areaName:
参数,因此将每个路由限制为一个区域.我不明白如何使用适用于多个区域的一个路线.
I am trying to define a MapAreaControllerRoute()
that routes to multiple Areas. In ASP.NET Core 3.0, however, there is the areaName:
parameter that needs to be set, thus restricting each route to a single area. I don't understand how I can use one route that will work for multiple Areas.
我已经阅读了Stack Overflow上的许多问题,但这似乎是ASP.NET Core 3.0中的新要求.在ASP.NET Core< = 2.2中,您可以创建MapRoute()
而不定义集areaName
.
I have read through many issues here on Stack Overflow, but it seems that this is a new requirement in ASP.NET Core 3.0. In ASP.NET Core <= 2.2 you could create a MapRoute()
without defining a set areaName
.
现在,在我的Startup.cs
中,我将端点定义为:
As it is now, in my Startup.cs
, I define my endpoints as:
app.UseEndpoints(endpoints =>
{
endpoints.MapAreaControllerRoute(
name: "Area1",
areaName: "Area1",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
endpoints.MapAreaControllerRoute(
name: "Area2",
areaName: "Area2",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
当然,必须有一种方法来定义一条覆盖所有区域的路线吗?
Surely, there must be a way to define a single route to cover all Areas?
推荐答案
好,因此,在阅读了更多的链接后,事实证明是区域控制器缺少属性的情况! 通过使用以下标签标记控制器:
Ok, so after reading an additional bunch of links, it turns out to be a case of missing attributes for the area controllers! By tagging the controllers with the following tags:
[Area("Area1")]
[Route("Area1/[controller]/[action]")]
public class Area1Controller : Controller
{
public IActionResult Index()
{
return View();
}
}
并将路线更改为:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapAreaControllerRoute(
name: "areas",
areaName: "areas",
pattern: "{area}/{controller=Home}/{action=Index}/{id?}"
);
}
一切似乎都按预期进行.
everything seems to work as expected.
这篇关于如何定义到多个区域的端点路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!