从 .NET 8 WebApp 传递时,.net 标准类库中的 Session 为 Null

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

我有.NET 8 WebApp和.NET Standard 2.0类库。 我正在使用 System.WebAdapters 1.4,以便可以从 ASP.NET 4.8 WebApp 增量迁移到 .NET 8 WebApp。

我的.NET 8 WebApp 程序.cs

using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.SystemWebAdapters;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddSystemWebAdapters()
    .AddJsonSessionSerializer(options =>
    {
        // Serialization/deserialization requires each session key to be registered to a type
        options.RegisterKey<int>("IncidentID");
    });

builder.Services.Configure<KestrelServerOptions>(options =>
{
    options.AllowSynchronousIO = true;
});

// If using IIS:
builder.Services.Configure<IISServerOptions>(options =>
{
    options.AllowSynchronousIO = true;
});

// Add configuration services to access settings
var configuration = builder.Configuration;


var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseSystemWebAdapters();

app.UseAuthorization();

app.MapRazorPages().RequireSystemWebAdapterSession();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
         name: "ashxRoute",
                    pattern: "uicomponents/handlers/{*path}",
                    defaults: new { controller = "LegacyHandler", action = "ProcessRequest" }).RequireSystemWebAdapterSession();
});

app.Run();

我的控制器文件,

using Microsoft.AspNetCore.Mvc;
using company.SharedHandlers.Handlers;
using Microsoft.AspNetCore.SystemWebAdapters;

namespace SampleWebApp
{
    public class NoiseWordsController : Controller
    {
        //private readonly IHttpContextAccessor _httpContextAccessor;

        //public NoiseWordsController(IHttpContextAccessor httpContextAccessor, ISessionManager)
        //{
        //    _httpContextAccessor = httpContextAccessor;
        //}
        [Session]
        [Route("uicomponents/handlers/NoiseWords.ashx")]
        public IActionResult Index()
        {
            NoiseWords noiseWords = new NoiseWords();
            System.Web.HttpContext.Current.Session["IncidentID"] = "200";
            noiseWords.ProcessRequest(HttpContext);
            return View();

        }
    }
}

运行项目后,我得到了

InvalidOperationException: No service for type 'Microsoft.AspNetCore.SystemWebAdapters.ISessionManager' has been registered.
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<T>(IServiceProvider provider)
Microsoft.AspNetCore.SystemWebAdapters.SessionLoadMiddleware.ManageStateAsync(HttpContext context, ISessionStateFeature feature)
Microsoft.AspNetCore.SystemWebAdapters.PreBufferRequestStreamMiddleware.InvokeAsync(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

当我从控制器中删除 Session 属性时,还删除

RequireSystemWebAdapterSession()
。然后我在
System.Web.HttpContext.Current.Session["IncidentID"] = "200";

得到 NULL Session

我的目标是将本次会议传递到我的班级图书馆。

using System.Web;
using System.Xml.Linq;

namespace company.SharedHandlers.Handlers
{
    public class NoiseWords : BaseHandler
    {
        public string cleanString = null;

        protected override void DoProcess(HttpContext context)
        {
            // list of potential operations.
            switch (RequestParam("sp"))
            {
                case "NoiseWords":
                    context.Response.ContentType = "text/xml";
                    context.Response.Headers["CacheControl"] = "no-cache";
                    context.Response.AddHeader("Pragma", "no-cache");
                    context.Response.Headers["Expires"] = "-1";
                    context.Response.Write("NoiseWords operation");

                    break;
             
            }
        }
    }
}

在这里,在上面的方法中我应该能够访问会话信息(IncidentID)。

我该怎么办?

c# asp.net asp.net-core webforms session-state
1个回答
0
投票

创建一个接口,例如 ISessionStore。 将其放在公共位置,以便任何项目都可以访问它。

在网络核心项目中实现它,如下所示:

public class SessionStore:ISessionStore
{
 private readonly HttpContextAccessor _context;
 public SessionStore(HttpContextAccessor context)
 {
   _context = context
 }
  //Implement methods for getting and setting session data
}

然后向net core DI注册,并传递net standard和netcore库之间的接口。

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