1. Startup.cs 设置 Session 相关的内容
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Web { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); //Session 保存到内存 services.AddDistributedMemoryCache(); services.AddSession(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseCookiePolicy(); // 必须在 UseMvc 之前调用 app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Login}/{action=Index}/{id?}"); }); } } }2. 在创建验证码图片时设置 Session, 但在登录时获取不到 Session。
/// <summary> /// 获取图形验证码 /// </summary> /// <returns></returns> [HttpGet] public ActionResult GetAuthCode() { string code = string.Empty; byte[] byteArr = new VerifyCode().GetVerifyCode(out code); HttpContext.Session.SetString("VERFIY_CODE_TOKEN", code); return File(byteArr, @"image/png"); } [HttpPost] public ActionResult CheckLogin(string username, string password, string code) { try { string sessionCode = HttpContext.Session.GetString("VERFIY_CODE_TOKEN"); if (string.IsNullOrEmpty(sessionCode) || string.Compare(code, sessionCode, true) != 0) { throw new Exception("验证码错误,请重新输入"); } throw new Exception("登录成功了!"); } catch (Exception ex) { return Json(new AjaxResult { state = ResultType.error.ToString(), message = ex.Message }); } }实际断点跟踪时, 发现 Session.Id 前后都不一致了。
注: 验证码是 普通提交, 登录是 ajax 请求。
----------------------------------------------------------------------------------------------------------
解决方案:
去掉:
services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; });
