Microsoft.AspNetCore.Session已弃用 .NET6如何使用Session
2024-08-19
64
在 .NET 6 中,Microsoft.AspNetCore.Session 已弃用。在 .NET 6 中,微软官方建议使用 IDistributedCache 接口来实现会话。IDistributedCache 接口提供了一个通用的 API,用于在各种缓存存储中存储数据。如果我们只是用本地内存缓存的话,实现很简单,跟使用Microsoft.AspNetCore.Session包的时候一样,只是从.NET6开始不需要安装Microsoft.AspNetCore.Session包就可以实现Session了。
所以我们可以卸载Microsoft.AspNetCore.Session这个包。
下面是一个示例使用内存缓存实现Session,在Program.cs里注册和使用服务:
builder.Services.AddSession();
app.UseSession();
然后在代码里可以这样读写Session:
Request.HttpContext.Session.SetString("key", "value");
Request.HttpContext.Session.GetString("key");
下面是Microsoft.AspNetCore.Http.SessionExtensions支持的扩展方法:
namespace Microsoft.AspNetCore.Http
{
//
// 摘要:
// Extension methods for Microsoft.AspNetCore.Http.ISession.
public static class SessionExtensions
{
//
// 摘要:
// Gets a byte-array value from Microsoft.AspNetCore.Http.ISession.
//
// 参数:
// session:
// The Microsoft.AspNetCore.Http.ISession.
//
// key:
// The key to read.
public static byte[]? Get(this ISession session, string key);
//
// 摘要:
// Gets an int value from Microsoft.AspNetCore.Http.ISession.
//
// 参数:
// session:
// The Microsoft.AspNetCore.Http.ISession.
//
// key:
// The key to read.
public static int? GetInt32(this ISession session, string key);
//
// 摘要:
// Gets a string value from Microsoft.AspNetCore.Http.ISession.
//
// 参数:
// session:
// The Microsoft.AspNetCore.Http.ISession.
//
// key:
// The key to read.
public static string? GetString(this ISession session, string key);
//
// 摘要:
// Sets an int value in the Microsoft.AspNetCore.Http.ISession.
//
// 参数:
// session:
// The Microsoft.AspNetCore.Http.ISession.
//
// key:
// The key to assign.
//
// value:
// The value to assign.
public static void SetInt32(this ISession session, string key, int value);
//
// 摘要:
// Sets a System.String value in the Microsoft.AspNetCore.Http.ISession.
//
// 参数:
// session:
// The Microsoft.AspNetCore.Http.ISession.
//
// key:
// The key to assign.
//
// value:
// The value to assign.
public static void SetString(this ISession session, string key, string value);
}
}
如果你想要存储对象的话,可以自己写一个扩展方法,然后把对象序列化后读写。
更新于:2个月前赞一波!2
相关文章
- ASP.NET Core 2.1中的ActionResult<T>
- .NET Core 3.0创建一个单独的可执行文件
- 在ASP.NET Core 2.1中使用HttpClientFactory的3种方法
- .NET Core MVC应用程序创建教程
- .NET Core中的File和PhysicalFile
- .NET Core 读取配置文件方法
- .NET Core 管道模型中间件及管道模拟实现
- ASP.NET Core多环境配置
- .NET Core 日志配置,NLog配置示例
- .NET Core SkiaSharp替代System.Drawing的用法
- .NET Core 3.X路由中间件和终结点中间件
- .Net报错Could not find a part of the path bin\roslyn\csc.exe
- IIS中.NET Core报错HTTP Error 500.31 - ANCM Failed to Find Native Dependencies
- .NET Core分部视图PartialView用法
- .NET Core 视图组件Component用法
- ASP.NET Core的三种部署方式
- .NET Core中使用System.Drawing处理图像
- .NET Core Razor Page ajax请求返回400 Bad request
- .NET Core上传文件报Access xxx.tmp is denied错误
- ASP.NET Core 使用Razor code blocks替代@helper
文章评论
评论问答