.NETCore和.NET5 MVC使用 Session


.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开发框架网发布内容,转载请附上原文出处连接
管理员
上一篇:服务器安全:限制外网访问解决方案
下一篇:.NETCore和.NET5 MVC解析获取appsettings.json数据
评论列表

发表评论

评论内容
昵称:
关联文章

.NETCore.NET5 MVC使用 Session
.NETCore.NET5 MVC 控制器中判断是否登录
.NETCore.NET5 MVC解析获取appsettings.json数据
ASP.NET MVCASP.NET Core MVC中获取当前URL/Controller/Action
在Winform项目Web API的.NetCore项目中使用Serilog 来记录日志信息
ASP.NET MVC快速入门(一)
Asp.NetCore3.1开源项目升级为.Net6.0
.net core MVC 使用 jquery ajax请求 Post json
.NET Core MVC中间件使用记录日志
.NETCore动态解析Razor代码cshtml代码解析RazorEngine.NetCore
浅析.netcore中的Configuration
ASP.NET MVC使用@Url.Action 多个参数中间&被URL编码了
Asp.net 微信H5唤起支付支付回调
.NETCore-winform 判断是否设计模式
使用Hot Chocolate.NET 6构建GraphQL应用(2) —— 实体相关功能实现
使用.NET 6开发TodoList应用(31)——实现基于Github ActionsACI的CI/CD
使用.NET 6开发TodoList应用(26)——实现ConfigurationOption的强类型绑定
asp.net - 在 ASP.NET Core MVC 中嵌套 TagHelper
ASP.NET+MVC入门踩坑笔记 (一) 创建项目 项目配置运行 以及简单的Api搭建
VS调试运行ASP.NET MVC项目,上传静态资源图片404问题,Debug路径

联系我们
联系电话:15090125178(微信同号)
电子邮箱:garson_zhang@163.com
站长微信二维码
微信二维码