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

如何在ASP.NET WebForms与ASP.NET Core Web API间共享会话值?

排查ASP.NET WebForms与Core WebAPI会话共享的配置遗漏

.NET 4.8 WebForms端检查

  • Session状态模式必须非进程内
    InProc模式的Session仅存在于当前应用进程,无法跨应用共享。必须配置为StateServer或SQLServer:
    <!-- StateServer模式示例 -->
    <sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" cookieless="false" timeout="20" />
    <!-- SQLServer模式需先运行aspnet_regsql.exe创建会话数据库 -->
    <sessionState mode="SQLServer" sqlConnectionString="Data Source=.;Initial Catalog=ASPState;Integrated Security=True" timeout="20" />
    
  • SystemWebAdapters配置节必须完整
    Web.config中需添加对应配置节并启用会话支持:
    <configSections>
      <section name="systemWebAdapters" type="Microsoft.AspNetCore.SystemWebAdapters.Configuration.SystemWebAdaptersSection, Microsoft.AspNetCore.SystemWebAdapters" />
    </configSections>
    
    <systemWebAdapters>
      <session enableSessionState="true" />
    </systemWebAdapters>
    
  • Global.asax初始化不能少
    在Application_Start中初始化适配器:
    protected void Application_Start(object sender, EventArgs e)
    {
        Microsoft.AspNetCore.SystemWebAdapters.SystemWebAdapters.Initialize();
        // 其他业务初始化代码
    }
    
  • 验证Session写入有效性
    检查设置Session的代码是否正确写入,同时输出Session.SessionID,和Core端请求的SessionID对比是否一致:
    Session["UserName"] = "TestUser";
    Response.Write($"WebForms SessionID: {Session.SessionID}");
    

.NET 6 Core WebAPI端检查

  • NuGet包版本要匹配
    确保安装Microsoft.AspNetCore.SystemWebAdapters和Microsoft.AspNetCore.SystemWebAdapters.SessionState,版本需与WebForms端的包版本一致。
  • 中间件顺序严格遵循
    中间件加载顺序错误会导致会话无法读取,必须按以下顺序配置:
    var builder = WebApplication.CreateBuilder(args);
    
    // 配置适配器会话,模式与WebForms端一致
    builder.Services.AddSystemWebAdapters()
        .AddSessionState(options =>
        {
            options.Mode = SessionStateMode.StateServer;
            options.StateConnectionString = "tcpip=127.0.0.1:42424";
            // SQLServer模式替换为:
            // options.Mode = SessionStateMode.SqlServer;
            // options.SqlConnectionString = builder.Configuration.GetConnectionString("ASPState");
        });
    
    builder.Services.AddSession();
    builder.Services.AddControllers();
    
    var app = builder.Build();
    
    // 中间件顺序:适配器→Session→路由→授权→控制器
    app.UseSystemWebAdapters();
    app.UseSession();
    
    app.UseRouting();
    app.UseAuthorization();
    
    app.MapControllers();
    
    app.Run();
    
  • Cookie配置必须完全一致
    两个应用的Session Cookie参数必须匹配,否则浏览器不会共享Cookie:
    "SystemWebAdapters": {
      "Cookie": {
        "Name": "ASP.NET_SessionId", // 和WebForms的SessionCookie名称一致
        "Domain": ".yourdomain.com", // 跨域时设根域名,同域可留空
        "Path": "/"
      }
    }
    
  • 必须使用适配器的Session访问器
    不能用Core原生ISession,要通过ISystemWebAdapterSessionAccessor读取WebForms的Session:
    [ApiController]
    [Route("api/session")]
    public class SessionController : ControllerBase
    {
        private readonly ISystemWebAdapterSessionAccessor _sessionAccessor;
    
        public SessionController(ISystemWebAdapterSessionAccessor sessionAccessor)
        {
            _sessionAccessor = sessionAccessor;
        }
    
        [HttpGet("username")]
        public IActionResult GetUserName()
        {
            var userName = _sessionAccessor.Session?["UserName"];
            // 同时输出Core端的SessionID,和WebForms端对比
            var sessionId = _sessionAccessor.Session?.SessionID;
            return Ok(new { UserName = userName, SessionID = sessionId });
        }
    }
    

通用验证要点

  • 检查Cookie一致性
    用浏览器F12查看两个应用的ASP.NET_SessionId值是否完全相同,Cookie的Domain、Path是否符合预期,没有被浏览器拦截。
  • StateServer服务状态
    若用StateServer模式,确保ASP.NET State Service已启动(服务管理器中设置为自动启动)。
  • SQLServer权限验证
    若用SQLServer模式,确保Core应用的运行账户有ASPState数据库的读写权限。
  • 版本兼容性
    避免SystemWebAdapters版本跨大版本差异,否则会导致序列化失败无法读取Session。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 06:23:22