Asp.net core如何使用Session
阿新 • • 發佈:2018-03-07
host con pre ner mvc -s bsp bubuko 使用
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(); services.AddSession(options=> { options.Cookie.Name= ".AdventureWorks.Session"; options.IdleTimeout = TimeSpan.FromSeconds(10);//設置session的過期時間 options.Cookie.HttpOnly = true; } ); 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(); } }
Asp.net core如何使用Session