通过SystemWebAdapter共享Session时,能否仅注册.NET Core所需变量?
问题:SystemWebAdapter仅注册.NET Core所需Session变量是否可行?
我们的ASP.NET WebForms项目包含大量Session变量,按照SystemWebAdapter的要求,需在Application_Start中通过AddJsonSessionSerializer注册这些变量。请问是否可以仅注册.NET Core项目实际需要的Session变量?尝试不注册全部变量时,出现了"Unknown session keys"错误。
ASP.NET代码片段(仅计划共享Employee变量)
protected void Application_Start(object sender, EventArgs e) { SystemWebAdapterConfiguration.AddSystemWebAdapters(this) .AddJsonSessionSerializer(options => { options.RegisterKey<ArrayList>("Employee"); }) .AddRemoteAppServer( options => { options.ApiKey = "4ffb49b3-2aa3-40b3-96ca-1b5331aab2dc"; } ).AddSessionServer(); } protected void Session_Start(object sender, EventArgs e) { System.Web.HttpContext.Current.Session["Company"] = "ABC"; System.Web.HttpContext.Current.Session["Employee"] = "John"; }
.NET Core Program.cs代码片段
using Core; using System.Collections; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); builder.Services.AddTransient<GlobalExceptionHandlerMiddleware>(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddSystemWebAdapters() .AddJsonSessionSerializer(options => { options.RegisterKey<ArrayList>("Employee"); }) .AddRemoteAppClient(options => { options.RemoteAppUrl = new Uri("http://192.168.56.1"); options.ApiKey = "4ffb49b3-2aa3-40b3-96ca-1b5331aab2dc"; }).AddSessionClient(); var app = builder.Build(); app.UseSwagger(); app.UseSwaggerUI(); app.UseMiddleware<GlobalExceptionHandlerMiddleware>(); app.UseAuthorization(); app.UseSystemWebAdapters(); app.MapControllers(); app.Run();
解决方案
可以仅注册.NET Core需要的Session变量,你遇到的"Unknown session keys"错误是因为ASP.NET端的Session序列化器会尝试处理所有已存在的Session键,哪怕你只注册了部分。解决方法是在ASP.NET端配置序列化器时,显式忽略那些不需要共享的Session键:
修改ASP.NET端的配置
在AddJsonSessionSerializer中添加options.IgnoreKey("Company"),让序列化器跳过未注册的键,只处理指定的Employee:
protected void Application_Start(object sender, EventArgs e) { SystemWebAdapterConfiguration.AddSystemWebAdapters(this) .AddJsonSessionSerializer(options => { options.RegisterKey<ArrayList>("Employee"); options.IgnoreKey("Company"); // 忽略不需要共享的Session键 }) .AddRemoteAppServer( options => { options.ApiKey = "4ffb49b3-2aa3-40b3-96ca-1b5331aab2dc"; } ).AddSessionServer(); }
注意事项
- ASP.NET和.NET Core两端注册的Session键及其类型必须完全一致,比如这里的
Employee必须都注册为ArrayList类型 - 如果有多个不需要共享的键,可以多次调用
IgnoreKey,或者使用IgnoreKeys传入键的集合(如options.IgnoreKeys(new[] { "Company", "OtherKey" }))
这样配置后,ASP.NET端只会序列化并共享你指定的Session键,忽略其他未注册的键,就不会再触发"Unknown session keys"错误了。
内容的提问来源于stack exchange,提问作者user25654022
相关产品推荐
相关产品推荐

