Homepage which generates following a" /> Homepage which generates following a" /> Homepage which generates following a"/>

How asp-area tag helper works with area routing?

2.3k Views Asked by At

I have following HTML

<a asp-area="Admin" asp-controller="Page" asp-action="PageTexts" asp-route-pageId="1">
    Homepage
</a>

which generates following a attribute with wrong URL address, because area is used as an parameter and not as an directory, so following code does not work.

<a href="/Page/PageTexts?pageId=1&area=Admin">Homepage</a>

instead what I need is this URL, with admin part as a URL prefix

/admin/page/pagetexts?pageId=1

My routing in startup.cs is following

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

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

                endpoints.MapRazorPages();
            });

My Area folder structure is following

enter image description here

And my Admin controllers has Area annotation attribute

namespace Web.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class PageController : Controller

what am I missing ?

1

There are 1 best solutions below

0
Muflix On

I fixed the UseEndpoints middleware, where I switch MapControllerRoute with MapAreaControllerRoute and now it works as it should.

app.UseEndpoints(endpoints =>
{
      endpoints.MapAreaControllerRoute(
             name: "Admin",
             areaName: "Admin",
             pattern: "Admin/{controller=Admin}/{action=Index}/{id?}");

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

      endpoints.MapRazorPages();
});