3
Answers

Area In asp.net core

mina shaker

mina shaker

Oct 04
620
1

Hi,

I was reading about routing in MVC and came across a section on areas. What confused me was that after creating an area folder, I couldn’t use the controllers in the root directory. Instead, I had to use only the controllers inside the area folder.

Answers (3)
3
Anupam Maiti

Anupam Maiti

180 10.7k 3.5m Oct 05

In ASP.NET Core MVC, when you create an Area, it organizes controllers separately. That’s why you can’t use root-level controllers inside an Area. To access both, you need to set up separate routes—one for the Area and another for the root controllers—to make them work together.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

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

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

app.Run();

Accepted
2
Jayraj Chhaya

Jayraj Chhaya

303 6k 92.9k Oct 04

In ASP.NET Core MVC, areas are designed to help organize your application into smaller, manageable sections, particularly for larger applications. When you create an area, it introduces a new routing convention that isolates the controllers and views within that area.

This means that when you define an area, the routing system looks for controllers specifically within that area folder. For example, if you have an area named "Admin," the routing will prioritize controllers located in Areas/Admin/Controllers. As a result, controllers in the root directory are not directly accessible unless you explicitly define routes for them.

To access controllers in the root directory while using areas, you can define custom routes in your Startup.cs file. 

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

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

This setup allows you to maintain both area-specific and root-level controllers effectively.

1
mina shaker

mina shaker

1.1k 233 11k Oct 08

@Anupam Maiti  should i include the `{area:exists}` in the main class or this is a placeholder for somthing