.Net Core MVC 2.1 中是否有等效的会话启动?

doo*_*deb 6 asp.net-mvc asp.net-core-mvc .net-core

在 MVC 5 中,您可以在会话开始时为 global.asx 中的会话分配一个值。有没有办法在 .Net Core MVC 中做到这一点?我已经配置了会话,但在中间件中似乎每个请求都会被调用。

Jef*_*nie 5

nercan 的解决方案可以工作,但我认为我找到了一个需要更少代码并且可能具有其他优点的解决方案。

首先,像这样包装 DistributedSessionStore:

using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Session;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;

public interface IStartSession
{
    void StartSession(ISession session);
}

public class DistributedSessionStoreWithStart : ISessionStore
{
    DistributedSessionStore innerStore;
    IStartSession startSession;
    public DistributedSessionStoreWithStart(IDistributedCache cache, 
        ILoggerFactory loggerFactory, IStartSession startSession)
    {
        innerStore = new DistributedSessionStore(cache, loggerFactory);
        this.startSession = startSession;
    }

    public ISession Create(string sessionKey, TimeSpan idleTimeout, 
        TimeSpan ioTimeout, Func<bool> tryEstablishSession, 
        bool isNewSessionKey)
    {
        ISession session = innerStore.Create(sessionKey, idleTimeout, ioTimeout,
             tryEstablishSession, isNewSessionKey);
        if (isNewSessionKey)
        {
            startSession.StartSession(session);
        }
        return session;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在 Startup.cs 中注册这个新类:

class InitSession : IStartSession
{
    public void StartSession(ISession session)
    {
        session.SetString("Hello", "World");
    }
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        ...
        services.AddSingleton<IStartSession, InitSession>();
        services.AddSingleton<ISessionStore, DistributedSessionStoreWithStart>();
        services.AddSession();
        ...
    }
Run Code Online (Sandbox Code Playgroud)

完整代码在这里: https://github.com/SurferJeffAtGoogle/scratch/tree/master/StartSession/MVC