1. NUGET包引用 icrosoft.AspNetCore.Session
2.Startup中新增一下程式碼:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSession(); //新增session }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); //訪問wwwroot下的檔案 app.UseSession(); //使用session app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
3.控制器中使用Session
using Microsoft.AspNetCore.Http; //新增引用
HttpContext.Session.SetString(“key”, “value”); //設定Session
var value = HttpContext.Session.GetString(“key”); //獲取Session