How to define an endpoint route to multiple areas

后端 未结 2 882
生来不讨喜
生来不讨喜 2021-01-04 19:20

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

相关标签:
2条回答
  • 2021-01-04 20:00

    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();
        }
    }
    

    and changing the routes to:

            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.

    0 讨论(0)
  • 2021-01-04 20:05

    You can write a generic pattern for areas using MapControllerRoute():

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "areas",
            pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
        );
        endpoints.MapDefaultControllerRoute();
    });
    

    Then the area controllers just need the Area attribute:

    [Area("AreaName")]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
    
    0 讨论(0)
提交回复
热议问题