How do I use an Area
in ASP.NET Core?
I have an app that needs an Admin section. This section requires its Views to be placed in that area. All requests that start with Admin/
will need to be redirected to that area.
How do I use an Area
in ASP.NET Core?
I have an app that needs an Admin section. This section requires its Views to be placed in that area. All requests that start with Admin/
will need to be redirected to that area.
In order to include an Area in an ASP.NET Core app, first we need to include a conventional route in the
Startup.cs
file (It's best to place it before any non-area route):In Startup.cs/Configure method:
Then make a folder named
Areas
in the app root and make another namedAdmin
inside the former, also make these folders insideAdmin
(ViewComponent is optional):Now we create a controller inside the
Controllers
folder namedAdminController
, the content can be like:Now in order for that to work, you'll need to create Views for all actions that return one. The hierarchy for views is just like what you have in a non-area Views folder:
Now, you should be good to go!
Question: What if I what to have another controller inside my Area?
Answer:
Just add another controller beside
AdminController
and make sure the routes are like the following:The important part is
[Route("admin/[controller]")]
. With that you can keep the style of routing toadmin/controller/action/...
Use this pattern in Configure method in Startup.Cs, as its full routing manner:
In Core 3.1 you should use below code in ConfigureServices method: