.NET Core 中 Session的使用

xiaoxiao2021-02-28  95

原文链接:http://beidouxun.com/Articles/Details/50bd1241-bc05-43df-9cbb-d5c00ced33ac

.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");

转载请注明原文地址: https://www.6miu.com/read-71912.html

最新回复(0)