.Net Core MVC 2.1中是否有等效的会话启动? [英] Is there a session start equivalent in .Net Core MVC 2.1?

查看:82
本文介绍了.Net Core MVC 2.1中是否有等效的会话启动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MVC 5中,您可以在会话启动时在global.asx中为会话分配一个值。您是否可以在.Net Core MVC中做到这一点?我已经配置了会话,但是在中间件中似乎可以在每个请求上调用它。

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.

推荐答案

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

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

首先,像这样包装DistributedSessionStore:

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

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

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

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

这篇关于.Net Core MVC 2.1中是否有等效的会话启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆