2025年3月28日 星期五 甲辰(龙)年 月廿七 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > .net

Microsoft.AspNetCore.Session已弃用 .NET6如何使用Session

时间:02-06来源:作者:点击数:39

在 .NET 6 中,Microsoft.AspNetCore.Session 已弃用。在 .NET 6 中,微软官方建议使用 IDistributedCache 接口来实现会话。IDistributedCache 接口提供了一个通用的 API,用于在各种缓存存储中存储数据。如果我们只是用本地内存缓存的话,实现很简单,跟使用Microsoft.AspNetCore.Session包的时候一样,只是从.NET6开始不需要安装Microsoft.AspNetCore.Session包就可以实现Session了。

Microsoft.AspNetCore.Session已弃用 .NET6如何使用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);
  • }
  • }

如果你想要存储对象的话,可以自己写一个扩展方法,然后把对象序列化后读写。

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门