ASP.NET Core 6.0 MVC Tutorial Day 5
Learning Objective: Let’s separate admin panel and frontend website using Area Concepts.
To create new Area (eg. Admin Panel folder) Follow the steps:
Right Click on application name from solution explorer >> Select Add >> Select New Scaffolded Item >> select MVC Area from middle pane of dialog box >> Enter Name of Area (eg. Admin) >> Click Ok.
So you have created new Area or in another word you have create new folder which can be accessible using online url, but for the access you need to do one more settings as follow: (Update Program.cs) (You need to add endpoint)
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Now its time to create new Controller into Area. You can create new controller, if your controller name is same as you have previously created for the front end website then you need to specify the details like as follow:
using Microsoft.AspNetCore.Mvc;
namespace WebApplication1.Areas.Admin.Controllers
{
[Area("Admin")]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
}