Create ASP.NET Core MVC Project
On the Visual Studio, create new ASP.NET Core MVC Web Application project
Select Empty Template
Click Ok 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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
namespace LearnASPNETCoreMVCWithRealApps.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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LearnASPNETCoreMVCWithRealApps.Middlewares;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace LearnASPNETCoreMVCWithRealApps
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSession();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseSession();
app.UseMiddleware<AuthenticationMiddleware>();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace LearnASPNETCoreMVCWithRealApps.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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
namespace LearnASPNETCoreMVCWithRealApps.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 razor views as below:
Home Views
In Views/Home folder, create new view named Index.cshtml as below:
@{
Layout = null;
}
<!DOCTYPE html>
<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:
@{
Layout = null;
}
<!DOCTYPE html>
<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:
@{
Layout = null;
}
@using Microsoft.AspNetCore.Http;
<!DOCTYPE html>
<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 System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace LearnASPNETCoreMVCWithRealApps.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:
@{
Layout = null;
}
<!DOCTYPE html>
<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 MVC 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
References
I recommend you refer to the books below to learn more about the knowledge in this article:
- Programming Microsoft ASP.NET 2.0 Core Reference
- Pro ASP.NET Core MVC
- Pro ASP.NET Core MVC 2
- .NET Core in Action