NET 10 集成Session

首先,你需要在Program 文件中的Main 方法中添加Session 服务:

csharp 复制代码
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSession(options =>
{
	options.IdleTimeout = TimeSpan.FromSeconds(10); // 设置Session 过期时间
	options.Cookie.HttpOnly = true;
	options.Cookie.IsEssential = true;
});

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.UseSession(); // 使用Session 中间件
app.MapControllers();
app.Run();

接下来,你可以在Controller 中使用HttpContext.Session 来设置和获取Session:

csharp 复制代码
public class HomeController : Controller
{
	public IActionResult Index()
	{
		// 设置Session
		HttpContext.Session.SetString("Name","Test");
		return View();
	}
	public IActionResult Privacy()
	{
		// 获取Session
		var name = HttpContext.Session.GetString("Name");
		ViewData["Name"] = name;
		return View();
	}
}

在上述代码中,我们首先在ConfigureServices 方法中添加了Session 服务,并设置了Session 的过期时间和Cookie 的属性。

然后在Configure 方法中使用了Session 中间件。最后在HomeController 中设置和获取了Session。

相关推荐
小七-七牛开发者9 小时前
TokenPilot:让 LLM Agent 长会话成本降 60%+ 的上下文管理
缓存·agent·token·context·上下文·推理成本
唐青枫15 小时前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫2 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
Caco_D2 天前
一行代码抓遍全网 20 个热榜!Aneiang.Pa 4.0 发布 — 极简 .NET 爬虫库
爬虫·.net
咕白m6252 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
小码编匠2 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫4 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
ofoxcoding7 天前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
2601_962072558 天前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos