.NET Core 和框架通过 SystemWebAdapter 共享特定的会话变量

问题描述 投票:0回答:1

我们的 ASP.NET Webforms 项目有许多会话变量。根据

SystemWebAdapter
,我需要在
AddJsonSessionSerializer
中按
Application_Start
列出它们。

我是否可以将它们限制为仅在 .NET Core 项目中使用?

我尝试不列出所有这些并收到此错误:“未知的会话密钥

这是包含两个会话变量的 ASP.NET 代码快照:

Company
Employee
。但只有
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";
}

这是

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();

谢谢

asp.net asp.net-core session share
1个回答
0
投票

在我的本地测试后,我发现您似乎缺少

RequireSystemWebAdapterSession
,也许您在控制器中使用
[Session]
属性。并且您的网络表单应用程序中没有
Company
Register Key
信息。

这是适合您的工作示例。

网页表格

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;

namespace WebApplication1
{
    public class Global : HttpApplication
    {
        void Application_Start(object sender, EventArgs e)
        {
            SystemWebAdapterConfiguration.AddSystemWebAdapters(this)
           .AddJsonSessionSerializer(options => {
               options.RegisterKey<string>("Company");
               options.RegisterKey<ArrayList>("Employee");
           })
           .AddRemoteAppServer(options =>
           {
               options.ApiKey = "68aba9ab-0d19-4b0a-952e-70a84f5113c2";
           })
           .AddSessionServer();
            // Code that runs on application startup
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

默认.aspx.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Session["Company"] = "ABC";
            ArrayList employeeData = new ArrayList();
            employeeData.Add("John Doe");
            employeeData.Add("Jane Smith");
            HttpContext.Current.Session["Employee"] = employeeData;
        }
    }
}

ASP.NET核心API

using System.Collections;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});


builder.Services.AddSystemWebAdapters()
    .AddJsonSessionSerializer(options => {
        options.RegisterKey<string>("Company");
        options.RegisterKey<ArrayList>("Employee");
    })
    .AddRemoteAppClient(options => {
        options.RemoteAppUrl = new Uri("https://localhost:44394"); 
        options.ApiKey = "68aba9ab-0d19-4b0a-952e-70a84f5113c2";
    }).AddSessionClient();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseSession();
app.UseAuthorization();
app.UseSystemWebAdapters();

app.MapControllers().RequireSystemWebAdapterSession();

app.Run();

SessionTestController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SystemWebAdapters;
using System.Collections;

namespace WebApplication2.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class SessionTestController : ControllerBase
    {
        [HttpGet("GetSessionValue")]
        public IActionResult GetSessionValue()
        {
            var sessionValue = System.Web.HttpContext.Current?.Session?["Company"].ToString();
            if (sessionValue == null)
            {
                return NotFound("Company not found in session.");
            }

            return Ok(new { TestSession = sessionValue });
        }
        [HttpGet("GetEmployeeData")]
        public IActionResult GetEmployeeData()
        {
            var employeeData = System.Web.HttpContext.Current.Session?["Employee"] as ArrayList;
            if (employeeData == null)
            {
                return NotFound("Employee data not found in session.");
            }

            return Ok(new { Employee = employeeData });
        }
    }
    
}

测试结果

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.