How To Use An Area In ASP.NET Core

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 the method.

  1. app.UseMvc(routes =>  
  2. {  
  3.     routes.MapRoute("areaRoute""{area:exists}/{controller=Admin}/{action=Index}/{id?}");  
  4.     routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");  
  5. });   

Then, make a folder named Areas in the app root and make another directory named Admin inside the former. Inside the admin folder, create the following folders (ViewComponent is optional).

Now, we will create a Controller inside the Controllers folder named AdminController.

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 want to have another Controller inside my Area?

Answer -

Just add another Controller beside AdminController and make sure the routes are like the following,

  1. [Area("Admin")]  
  2. [Route("admin/[controller]")]  
  3. public class ProductsController: Controller {  
  4.     publicProductsController() {  
  5.             //  
  6.         }  
  7.         [Route("{page:int?}")]  
  8.     publicIActionResult Index() {  
  9.         returnView();  
  10.     }  
  11. }   

The important part is [Route("admin/[controller]")]. With that, you can keep the style of routing to admin /controller/ action/.

Ebook Download
View all
Learn
View all