.NETCore和.NET5 MVC使用 Session
.NETCore MVC 项目使用 Session
启用Session配置
在 Startup.cs
中配置启用Session
ConfigureServices
方法中添加 services.AddSession();
C# 全选
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
// 启用session
services.AddSession();
}
Configure
方法中增加 app.UseSession();
C# 全选
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
// 使用Session
app.UseSession();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
使用 Session
1) 通过 session 判断是否登录
C# 全选
/// <summary>
/// 判断用户是否已经登录(解决Session超时问题)
/// </summary>
public bool IsUserLogin()
{
//如果Session为Null
string str = HttpContext.Session.GetString(GZKeys.SESSION_USER);
if (!String.IsNullOrWhiteSpace(str))
{
return true;
}
return false;
}
2) 成功登录后写入Session
C# 全选
HttpContext.Session.SetString(GZKeys.SESSION_USER, "true");
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 管理员