Search code examples
asp.net-mvc.net-coreasp.net-core-mvc

Is there a session start equivalent in .Net Core MVC 2.1?


In MVC 5 you could assign a value to session in global.asx when the session started. Is there a way you can do this in .Net Core MVC? I have session configured but in the middleware it seems to get called on every request.


Solution

  • nercan's solution will work, but I think I found a solution that requires less code and may have other advantages.

    First, wrap DistributedSessionStore like this:

    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;
        }
    }
    

    Then register this new class in 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();
            ...
        }
    

    Full code is here: https://github.com/SurferJeffAtGoogle/scratch/tree/master/StartSession/MVC