.NET Core中使用Session步骤如下:
1、安装Microsoft.AspNetCore.Session NuGet包
2、修改Startup.cs 添加相关服务,services.AddSession()和app.UseSession()
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultTokenProviders(); // Add application services. services.AddTransient<IEmailSender, EmailSender>(); //Add session services.AddSession(); services.AddMvc(); }
// 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(); app.UseBrowserLink(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseAuthentication(); app.UseSession(); app.UseMvc(routes => { //Default route routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
3、Session 用法
引用
using Microsoft.AspNetCore.Http;
Session写入
HttpContext.Session.SetString("key", "value");
Session读取
HttpContext.Session.GetString("key");