Asp.net core使用session:
在新建Asp.net core應用程序后,要使用session中間件,在startup.cs中需執行三個步驟:
1.使用實現了IDistributedcache接口的服務來啟用內存緩存。(例如使用內存緩存)
//該步驟需在addsession()調用前使用。
2.調用addsession方法

3.使用usesession回調(usesession需在useMvc()方法前調用)

具體代碼如下:
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.AddDistributedMemoryCache();//啟用session之前必須先添加內存 services.AddSession(options => { options.Cookie.Name= ".AdventureWorks.Session"; options.IdleTimeout = TimeSpan.FromSeconds(10);//設置session的過期時間 options.Cookie.HttpOnly = true;//設置在瀏覽器不能通過js獲得該cookie的值 } ); 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.UseSession(); app.UseMvc(); } }
