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

ASP.NET Web Forms与Blazor应用间的Session共享方案咨询

ASP.NET 4.7.2 与 Blazor 7.0 跨应用 Session 共享方案

方案一:分布式 Session 存储(推荐)

将两个应用的 Session 数据统一存储到分布式介质(如 Redis、SQL Server),打破进程内 Session 的隔离限制。

ASP.NET 4.7.2 配置

  1. 安装对应存储的 NuGet 包,例如 Redis 存储需安装 Microsoft.AspNet.SessionState.SessionStateModule.Redis
  2. 修改 web.config,配置 Session 状态为自定义 Provider,确保两个应用的 applicationName 一致:
<sessionState mode="Custom" customProvider="RedisSessionProvider">
  <providers>
    <add name="RedisSessionProvider" 
         type="Microsoft.Web.Redis.RedisSessionStateProvider"
         host="你的Redis地址"
         port="6379"
         accessKey="你的访问密钥(如果有)"
         ssl="false"
         databaseId="0"
         applicationName="你的电商应用标识"/>
  </providers>
</sessionState>

Blazor 7.0 配置

  1. 安装 Microsoft.AspNetCore.DataProtection.StackExchangeRedis 和 Microsoft.AspNetCore.Session NuGet 包
  2. 在 Program.cs 中配置分布式缓存与 Session,Cookie 名称需和 ASP.NET 4.7.2 保持一致:
var builder = WebApplication.CreateBuilder(args);

// 配置 Redis 分布式缓存
builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = "你的Redis地址:6379";
    options.InstanceName = "你的电商应用标识:";
});

// 配置 Session
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
    options.Cookie.Name = ".ASP.NET.Session"; // 与ASP.NET 4.7.2的Session Cookie名称匹配
});

var app = builder.Build();

// Session 中间件需放在路由中间件之前
app.UseSession();
app.UseRouting();

// 其他中间件配置...
  • Blazor Server 可直接通过 HttpContext.Session 读写数据;Blazor WASM 需通过后端 API 代理操作 Session,因为客户端无法直接访问服务器 Session。

通过统一的 Cookie 标识 SessionID,配合自定义数据库存储实现跨应用 Session 共享。

  1. 统一 Cookie 配置

    • ASP.NET 4.7.2 在 web.config 中设置:
      <sessionState cookieName=".ASP.NET.Session" />
      <httpCookies domain=".你的域名.com" path="/" />
      
    • Blazor 在 Program.cs 中同步 Cookie 参数:
      builder.Services.AddSession(options =>
      {
          options.Cookie.Name = ".ASP.NET.Session";
          options.Cookie.Domain = ".你的域名.com";
          options.Cookie.Path = "/";
          // 其他超时等配置
      });
      
  2. 实现统一 Session 操作接口
    定义 ISessionService 接口,两个应用均通过该接口读写 Session 数据,底层用同一数据库关联 SessionID 存储键值对:

    • ASP.NET 4.7.2(VB.NET)示例:
      Public Class SessionService Implements ISessionService
          Public Function GetSessionValue(key As String) As String Implements ISessionService.GetSessionValue
              Dim sessionId = HttpContext.Current.Request.Cookies(".ASP.NET.Session").Value
              ' 从数据库查询对应sessionId的key值
          End Function
      
          Public Sub SetSessionValue(key As String, value As String) Implements ISessionService.SetSessionValue
              Dim sessionId = HttpContext.Current.Request.Cookies(".ASP.NET.Session").Value
              ' 将key-value存入数据库对应sessionId的记录
          End Sub
      End Class
      
    • Blazor Server 示例:
      public class SessionService : ISessionService
      {
          private readonly IHttpContextAccessor _httpContextAccessor;
          private readonly IDbConnection _dbConnection;
      
          public SessionService(IHttpContextAccessor httpContextAccessor, IDbConnection dbConnection)
          {
              _httpContextAccessor = httpContextAccessor;
              _dbConnection = dbConnection;
          }
      
          public string GetSessionValue(string key)
          {
              var sessionId = _httpContextAccessor.HttpContext.Session.Id;
              // 从数据库查询对应sessionId的key值
          }
      
          public void SetSessionValue(string key, string value)
          {
              var sessionId = _httpContextAccessor.HttpContext.Session.Id;
              // 将key-value存入数据库对应sessionId的记录
          }
      }
      

方案三:参考 eShopOnBlazor 的共享 API 模式

搭建独立的 Session 管理 API,让 ASP.NET 和 Blazor 均通过调用该 API 操作 Session 数据:

  1. 新建 Web API 项目,实现 Session 的 CRUD 接口,底层用分布式存储(如 Redis)持久化数据
  2. ASP.NET 4.7.2 替换原有 Session 操作为 API 调用:
    Public Function GetOrderId() As String
        Dim sessionId = HttpContext.Current.Session.SessionID
        Using client As New HttpClient()
            Dim response = client.GetAsync($"https://你的SessionAPI地址/session/{sessionId}/OrderId").Result
            Return response.Content.ReadAsStringAsync().Result
        End Using
    End Function
    
  3. Blazor 中通过 HttpClient 调用同一 API:
    public async Task<string> GetOrderIdAsync()
    {
        var sessionId = _httpContextAccessor.HttpContext.Session.Id;
        var response = await _httpClient.GetAsync($"https://你的SessionAPI地址/session/{sessionId}/OrderId");
        return await response.Content.ReadAsStringAsync();
    }
    

关键注意事项

  • 确保两个应用的 DataProtection 密钥共享,否则 Cookie 无法跨应用解析。ASP.NET 4.7.2 可配置 DataProtection 持久化密钥,Blazor 需使用同一密钥存储。
  • Blazor WASM 无法直接操作服务器 Session,必须通过后端 API 代理完成。
  • 统一两个应用的 Session 超时时间,避免数据不一致。

内容的提问来源于stack exchange,提问作者Maximilian H Kim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 16:05:01