Asp.net core ASP.NET核心中的Session.IsNewSession
我正在将ASP.NET MVC应用程序迁移到ASP.NET Core 3.1 我有一个代码来检查我的控制器中的会话是否超时,如下所示:Asp.net core ASP.NET核心中的Session.IsNewSession,asp.net-core,session,Asp.net Core,Session,我正在将ASP.NET MVC应用程序迁移到ASP.NET Core 3.1 我有一个代码来检查我的控制器中的会话是否超时,如下所示: if (Session.IsNewSession) { 如何在ASP.NET Core中检查它 谢谢ISession的默认实现是DistributedSession。这不会公开IsNewSession的任何属性,尽管其构造函数接受名为isNewSessionKey的参数。因此,您可以使用reflection获取\u isNewSessionKey的私有字段来检
if (Session.IsNewSession) {
如何在ASP.NET Core中检查它
谢谢ISession的默认实现是
DistributedSession
。这不会公开IsNewSession
的任何属性,尽管其构造函数接受名为isNewSessionKey
的参数。因此,您可以使用reflection
获取\u isNewSessionKey
的私有字段来检查它。但这种方式不是很标准,将来可能会更改名称,而不会通知您任何设计时错误
你有几点需要截取并在这里获取信息。第一点是创建一个自定义的ISessionStore
(默认为DistributedSessionStore
),以拦截对ISessionStore.create的调用,该调用提供了对iNewSessionKey
的访问。您可以将该值捕获到请求功能中,就像框架在创建会话后如何设置ISessionFeature
一样。代码如下:
//create the feature interface & class
public interface ISessionExFeature {
bool IsNewSession { get; }
}
public class SessionExFeature : ISessionExFeature {
public SessionExFeature(bool isNewSession){
IsNewSession = isNewSession;
}
public bool IsNewSession { get; }
}
//the custom ISessionStore
public class CustomDistributedSessionStore : DistributedSessionStore, ISessionStore
{
readonly IHttpContextAccessor _httpContextAccessor;
public CustomDistributedSessionStore(IDistributedCache cache,
ILoggerFactory loggerFactory,
IHttpContextAccessor httpContextAccessor) : base(cache, loggerFactory)
{
_httpContextAccessor = httpContextAccessor;
}
ISession ISessionStore.Create(string sessionKey, TimeSpan idleTimeout, TimeSpan ioTimeout, Func<bool> tryEstablishSession, bool isNewSessionKey)
{
var httpContext = _httpContextAccessor.HttpContext;
if(httpContext != null)
{
var sessionExFeature = new SessionExFeature(isNewSessionKey);
httpContext.Features.Set<ISessionExFeature>(sessionExFeature);
}
return Create(sessionKey, idleTimeout, ioTimeout, tryEstablishSession, isNewSessionKey);
}
}
//register the custom ISessionStore inside Startup.ConfigureServices
services.Replace(new ServiceDescriptor(typeof(ISessionStore), typeof(CustomDistributedSessionStore), ServiceLifetime.Transient));
//an extension method to help get the ISessionExFeature conveniently
public static class SessionExFeatureHttpContextExtensions {
public static bool HasNewSession(this HttpContext context){
return context.Features.Get<ISessionExFeature>()?.IsNewSession ?? false;
}
}
截取和获取信息的另一点是自定义ISessionStore
和ISession
。这意味着您创建了一个子类DistributedSession
,并公开了IsNewSession
的属性。这可能需要更多的代码,但看起来更像是旧的获取信息的方式(直接从会话
而不是通过HttpContext
上的扩展方法)
if (HttpContext.HasNewSession()) {
//...
}