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 request
Areas Implementation in Routing First Create Area(Admin) using VS and add the following code into Startup.cs First Way to Implement:- Add Controller Login and Index Action and add Following Code, [Area(“Admin”)] is compulsory to add on controller level to perform asp.net areas Routing. Startup.cs
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Login}/{action=Index}/{id?}"
);
});
Note: Area routing must be placed first with non area routing, area: exists is compulsory to add area routing.
Controller Code:
[Area("Admin")]
public class LoginController : Controller
{
public IActionResult Index()
{
return Content("Area Admin Login Controller and Index Action");
}
}
This route may be called using http://localhost:111/Admin
Second Way to Implement Area Routing:- Add Following code into startup.cs.
app.UseMvc(routes =>
{
routes.MapAreaRoute(
name: "default",
areaName: "Guest",
template: "Guest/{controller}/{action}/{id?}",
defaults: new { controller = "GuestLogin", action = "Index" });
});
Create an Area “Guest”, Add “GuestLogin” Controller and “Index” Action and add the following code into the newly created controller.
[Area("Guest")]
public class GuestLoginController : Controller
{
public IActionResult Index()
{
return Content("Area Guest Login Controller and Index Action");
}
}
This route may be called using http://localhost:111/Guest
With .net core, following is needed to be added in the startup file if you are adding an area:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
After that you can just simply mark your area and route in the controller, i.e
[Area("Order")]
[Route("order")]
it works for me.