.Core中使用Session
.Core中使用Session
1.首先你需要安装NuGet包:Microsoft.AspNetCore.Session
2.在Startup.cs文件中添加代码。
public void ConfigureServices(IServiceCollection services) { services.AddSession(); services.AddControllersWithViews(); services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => false;//默认为true,改为false options.MinimumSameSitePolicy = SameSiteMode.None; }); }
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseSession(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
Session写入
HttpContext.Session.SetString("key", "value");
Session读取
HttpContext.Session.GetString("key")