ASP.NET Core MVC中无法使用Session存储邮箱的问题排查
Session设置后重定向回登录页的问题
我在登录控制器方法中尝试设置Session存储员工邮箱,代码无语法报错,但调试到Session设置代码行时,页面会自动重定向回登录页,无法进入OTP验证页面。后续在OTP验证方法中尝试读取Session值也无法正常工作。
登录控制器方法代码
[HttpPost] public IActionResult LoginFunc(Login model) { try { bool employeeIdExists = _DAL.EmployeeIdExists(model.RMEmployeeId); if (!employeeIdExists) { ViewBag.ErrEmployeeDoesntExists = "This Employee Id doesn't exist."; return View("~/Views/Home/Login.cshtml"); } else { _employeeEmailId = _DAL.GetEmailByEmployeeId(model.RMEmployeeId); string otp = GenerateOtp(6); //TempData["EmployeeEmailId"] = employeeEmailId; //TempData["Otp"] = otp; //HttpContext.Session.SetString("Otp", otp); //Using smtp here Login_DAL.SendOtpByEmail(otp, smtpHost, smtpPort, cMailId, cMailIDPassword, fromEmailId, configuration, _employeeEmailId); DateTime expiryDateTime = DateTime.Now.AddMinutes(30); _DAL.AddOtpData(_employeeEmailId, otp, expiryDateTime); //SendOtpByEmail(employeeEmailId, otp, smtpHost, smtpPort, cMailId, cMailIDPassword, fromEmailId); ViewBag.DisplayOtpModal = true; HttpContext.Session.SetString("EmployeeEmail", employeeEmailId); // return View("~/Views/Home/OtpPage.cshtml"); return RedirectToAction("VerifyOtpPage"); } } catch (Exception ex) { TempData["errorMessage"] = ex.Message; return View("~/Views/Home/Login.cshtml"); } }
OTP验证控制器方法代码
[HttpPost] public IActionResult VerifyOtp(VerifyOtp enteredOtp) { try { if (string.IsNullOrEmpty(enteredOtp.Otp)) { ModelState.AddModelError("Otp", "Please enter the Otp."); return View("~/Views/Home/OtpPage.cshtml"); } string employeeEmailId = HttpContext.Session.GetString("EmployeeEmail"); bool verifiedOtp = _DAL.VerifyOtp(enteredOtp.Otp, employeeEmailId); if (verifiedOtp) { // return View("~/Views/Home/HomeIndex.cshtml"); return RedirectToAction("HomeIndex", "Home"); // return View(); } else { ViewBag.DisplayOtpModal = true; ViewBag.IncorrectOtp = "Invalid or expired OTP."; return View("~/Views/Home/OtpPage.cshtml"); } } catch (Exception ex) { TempData["errorMessage"] = ex.Message; return View("~/Views/Home/OtpPage.cshtml"); } }
Startup.cs代码
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; using Microsoft.AspNetCore.Http; namespace WebApplicationFinal { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { // Configure your services here services.AddDistributedMemoryCache(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); services.AddMvc(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // Configure your middleware here app.UseRouting(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSession(); // This should be placed after UseRouting and before UseEndpoints app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=MainPageView}"); }); } } }
问题排查与解决建议
变量名不匹配问题
登录方法中获取邮箱的变量是_employeeEmailId,但设置Session时用的是未定义的employeeEmailId,这会导致Session存储空值,后续逻辑异常。修改Session设置代码:HttpContext.Session.SetString("EmployeeEmail", _employeeEmailId);中间件顺序错误
UseDeveloperExceptionPage()必须放在UseRouting()之前,否则异常处理无法覆盖路由后的逻辑,可能导致Session异常。调整Startup.cs的Configure方法:public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=MainPageView}"); }); }验证页面授权拦截
检查VerifyOtpPage对应的Action是否添加了[AllowAnonymous]特性,如果该页面被授权规则拦截,会自动重定向回登录页。Session Cookie配置优化
显式设置Session Cookie的SameSite属性,避免跨站Cookie丢失问题:services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(30); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; options.Cookie.SameSite = SameSiteMode.Lax; });
内容的提问来源于stack exchange,提问作者Ashley Ferns
相关产品推荐
相关产品推荐

