Create ASP.NET Core MVC 5 Project
On the Visual Studio, select Create a new project from Get Started
Select ASP.NET Core Web Application
Input Project Name and select Location for new project
Select ASP.NET Core 5.0 Version and select ASP.NET Core Empty Template. Click Create button to finish
Add Middleware
Create new folder named Middlewares. In this folder, create new middlewares as below:
Authentication Middleware
In Middlewares folder, create new class named AuthenticationMiddleware.cs as below:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace LearnASPNETCoreMVC5.Middlewares
{
// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
public class AuthenticationMiddleware
{
private readonly RequestDelegate _next;
public AuthenticationMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext httpContext)
{
var path = httpContext.Request.Path;
if(path.HasValue && path.Value.StartsWith("/admin"))
{
if (httpContext.Session.GetString("username") == null)
{
httpContext.Response.Redirect("/login/index");
}
}
return _next(httpContext);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class AuthenticationMiddlewareExtensions
{
public static IApplicationBuilder UseAuthenticationMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<AuthenticationMiddleware>();
}
}
}
Add Configurations
Open Startup.cs file and add new configurations as below:
using LearnASPNETCoreMVC5.Middlewares;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace LearnASPNETCoreMVC5
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSession();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Demo}/{action=Index}/{id?}");
});
}
}
}
Create Controller
Create new folder named Controllers. In Controllers folder, create new controller as below:
Home Controller
Create new controller named HomeController.cs as below:
using Microsoft.AspNetCore.Mvc;
namespace LearnASPNETCoreMVC5.Controllers
{
[Route("home")]
public class HomeController : Controller
{
[Route("")]
[Route("index")]
[Route("~/")]
public IActionResult Index()
{
return View();
}
}
}
Login Controller
Create new controller named LoginController.cs as below:
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace LearnASPNETCoreMVC5.Controllers
{
[Route("login")]
public class LoginController : Controller
{
[Route("")]
[Route("index")]
public IActionResult Index()
{
return View();
}
[HttpPost]
[Route("process")]
public IActionResult Process(string username, string password)
{
if (username != null && password != null && username.Equals("admin") && password.Equals("123"))
{
HttpContext.Session.SetString("username", username);
return View("Welcome");
}
else
{
ViewBag.error = "Invalid";
return View("Index");
}
}
}
}
Create Views
In Views folder, create new views as below:
Home Views
In Views/Home folder, create new view named Index.cshtml as below:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h3>Home Page</h3>
</body>
</html>
Login View
In Views/Login folder, create new view named Index.cshtml as below:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h3>Login Page</h3>
@ViewBag.error
<form method="post" asp-controller="login" asp-action="process">
<table cellpadding="2" cellspacing="2">
<tr>
<td>Username</td>
<td>
<input type="text" name="username" />
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name="password" />
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" value="Login" />
</td>
</tr>
</table>
</form>
</body>
</html>
Welcome Views
In Views/Login folder, create new view named Welcome.cshtml as below:
@using Microsoft.AspNetCore.Http;
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Welcome</title>
</head>
<body>
Welcome @Context.Session.GetString("username")
</body>
</html>
Create Area
In project, create new area named Admin. In this area, create new Controller and Views as below:
Product Controller
In Area\Admin\Controllers folder, create new controller named ProductController.cs as below:
using Microsoft.AspNetCore.Mvc;
namespace LearnASPNETCoreMVC5.Areas.Admin.Controllers
{
[Area("admin")]
[Route("admin/product")]
public class ProductController : Controller
{
[Route("")]
[Route("index")]
public IActionResult Index()
{
return View();
}
}
}
Index View
In Views/Product folder, create new view named Index.cshtml as below:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h3>Product Admin Page</h3>
</body>
</html>
Structure of ASP.NET Core MVC 5 Project
Run Application
Access Index action in Home controller with following url: http://localhost:48982/home/index
Output
Access Index action in Product controller in Admin area with following url: http://localhost:49328/admin/product/index without session
Output
Test with invalid account is username: abc and password: 123
Output
Test with valid account is username: admin and password: 123
Output
Access Index action in Product controller in Admin area with following url: http://localhost:49328/admin/product/index again
Output