You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6 Razor Pages获取Session返回Null问题求助

ASP.NET Core 6 Razor Pages Session重启丢失问题解决

问题根源

当前项目使用AddDistributedMemoryCache()作为Session的缓存存储,这是内存级缓存,项目停止重启后,内存中的所有缓存数据(包括Session)会被完全清空,这是该缓存类型的固有特性。你提到的.NET 3示例项目能正常保留Session,大概率是使用了持久化的分布式缓存方案(如SQL Server、Redis),而非内存缓存。

解决方案

要实现Session跨重启保留,需要将内存缓存替换为持久化的分布式缓存方案,以下是两种常用实现:

方案1:使用SQL Server分布式缓存

  1. 安装NuGet包:
    Install-Package Microsoft.Extensions.Caching.SqlServer
    
  2. 执行命令创建缓存所需的数据库表(替换YourConnectionString为你的项目数据库连接字符串):
    dotnet sql-cache create "YourConnectionString" dbo SessionCache
    
  3. 修改Program.cs中的缓存注册代码,将AddDistributedMemoryCache()替换为:
    builder.Services.AddDistributedSqlServerCache(options =>
    {
        options.ConnectionString = builder.Configuration.GetConnectionString("YourConnectionString");
        options.SchemaName = "dbo";
        options.TableName = "SessionCache";
    });
    

方案2:使用Redis分布式缓存(需Redis环境)

  1. 安装NuGet包:
    Install-Package Microsoft.Extensions.Caching.StackExchangeRedis
    
  2. 修改Program.cs中的缓存注册代码,将AddDistributedMemoryCache()替换为:
    builder.Services.AddStackExchangeRedisCache(options =>
    {
        options.Configuration = builder.Configuration.GetConnectionString("RedisConnection");
        options.InstanceName = "SampleInstance";
    });
    
    同时在appsettings.json中添加Redis连接字符串:
    "ConnectionStrings": {
        "RedisConnection": "localhost:6379"
    }
    

额外检查

确认Program.cs中中间件顺序正确,UseSession()需放在UseAuthentication()、UseAuthorization()之后,MapRazorPages()、UseEndpoints()之前,你的当前配置顺序是正确的,无需调整。

内容的提问来源于stack exchange,提问作者keyvan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 19:31:13