1、确保你的项目中包含 Microsoft.AspNetCore.Session 包。如果没有,可以通过 NuGet 包管理器安装:
dotnet add package Microsoft.AspNetCore.Session
2、注册session
public void ConfigureServices(IServiceCollection services) { services.AddDistributedMemoryCache(); // In-memory cache for session storage services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); services.AddControllersWithViews(); }
3、在 Configure 方法中,确保 UseSession 调用在 UseRouting 和 UseAuthorization 之前:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseSession(); // Ensure this is placed here app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
4、在控制器中完成登录,并写入Session,然后退转到主页面
public IActionResult Login(string username, string password) { // Assume validation of user credentials if (username == "user" && password == "password") // Simplified validation { HttpContext.Session.SetString("UserName", username); return RedirectToAction("Index", "Home"); } return View(); }
5、在控制器中完成退出逻辑,并销毁Session,然后跳转到登录页面
public IActionResult Logout() { HttpContext.Session.Remove("UserName"); return RedirectToAction("Index", "Home"); }
6、接下来,我们完成过滤器
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Filters; public class SessionAuthFilter : IActionFilter { public void OnActionExecuting(ActionExecutingContext context) { var username = context.HttpContext.Session.GetString("UserName"); if (string.IsNullOrEmpty(username)) { // Redirect to login page if not logged in context.Result = new RedirectToActionResult("Login", "Account", null); } } public void OnActionExecuted(ActionExecutedContext context) { // No action needed after the action method executes } }
注意,如果此处要配置为全局过滤器,需要在ConfigureServices中注册。
public void ConfigureServices(IServiceCollection services) { services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); services.AddControllersWithViews(options => { options.Filters.Add<SessionAuthFilter>(); // Register global filter }); }
如果只是在方法或者控制器上增加特性,则我们的过滤器需要继承:Attribute
public class AdminCheckLoginFilter : Attribute, IActionFilter