Search code examples
asp.net-core-mvc.net-6.0asp.net-mvc-routingasp.net-mvc-areas

.NET Core 6.0 Routing is Not working if i use areas


I have project with areas and normal controller in it. But Area routing is working but normal controller is not working.

Working, but Areas routing is returning 404 :

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

Working for Area routing but not root controller :

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

I have other 3 project with same scenarios but that are working but facing issue with my recently created project.


Solution

  • References : https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/areas?view=aspnetcore-6.0

    You have to specify two routes with different names.

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

    After that you have to use [Area] attribute to specify which Controller belongs to which Area.

     [Area("Admin")]