asp.net-mvc - .Net Core MVC 2.1 中是否有等效的会话开始?
问题描述
在 MVC 5 中,您可以在会话开始时为 global.asx 中的会话分配一个值。有没有办法在.Net Core MVC 中做到这一点?我已经配置了会话,但在中间件中,似乎每个请求都会调用它。
解决方案
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;
}
}
然后在 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
推荐阅读
- c++ - 将整数行直接读入向量
- c++ - std::function 如何接受具有相同函数调用运算符签名的所有函数对象?
- python - pandas.DataFrame 和 pandas.Series 对象对 pandas.get_dummies() 的作用不同
- sharepoint - 对象引用未设置为对象的实例 - Sharepoint 上的 SSRS
- javascript - 在函数中使用 if 语句的问题
- aws-sdk - 如何通过密钥而不是 id AWS APIGateway 获取 api 密钥
- php - 如何在 CodeIgniter 中使用带有 jquery 验证的 ajax 上传图像?
- typescript - 我可以使用固定键创建地图吗?
- javascript - 使用 Javascript 和 CSS 使 Ripple 按钮可点击
- json - Django - 如何在 RESTful API 中正确地流式传输矩阵?