Search code examples
c#.netasp.net-coreasp.net-core-mvcasp.net-mvc-areas

asp-action tag helper does not create the Area link properly with Endpoint Routing


i'm using .net core 3.1.1

in mvc area when i use asp-action like this

<a asp-action="Index2">Index2</a>

it does not properly create the link I want (Does not create area name)

The link it creates:

http://localhost:49770/Home/Index2

But this is the correct link:

http://localhost:49770/admin/Home/Index2

im using endpoint routing as follows:

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

            endpoints.MapAreaControllerRoute(
                "area",
                "Admin",
                "{area:exists}/{controller=Home}/{action=Index}/{id?}"

            );
        });

But when I use the older version of routing (UseMvc)as shown below, it creates the link correctly

 app.UseMvc(routes =>
    {
      routes.MapRoute(
        name : "areas",
        template : "{area:exists}/{controller=Home}/{action=Index}/{id?}"
      );
    });

Solution

  • You should modify the order to make the Areas route first :

    endpoints.MapAreaControllerRoute(
        "area",
        "Admin",
        "{area:exists}/{controller=Home}/{action=Index}/{id?}"
    
    
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    

    So that the <a asp-action="Index2">Index2</a> will create the link to an action method of the same area .