How to define an endpoint Route to multiple Areas

独自空忆成欢 提交于 2020-04-10 14:43:40

问题


I am trying to define a MapAreaControllerRoute that routes to multiple Areas, but in 3.0 there is the areaName: property that needs to be set. I don't understand how I can use ONE route to be valid for multiple Areas.

I have read through many issues here, but it seems that this is a new thing to MVC Core 3.0. In MVC Core <= 2.2 you could create a MapRoute without defining a set areaName.

As it is now, in 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 only ONE route to cover all Areas?

BR Per


回答1:


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.



来源:https://stackoverflow.com/questions/58352836/how-to-define-an-endpoint-route-to-multiple-areas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!