Asp.net core 控制器依赖项注入中的当前会话

Asp.net core 控制器依赖项注入中的当前会话,asp.net-core,asp.net-core-mvc,Asp.net Core,Asp.net Core Mvc,在startup.cs中,我有 services.AddScoped<ISession>(); 但是Isession不是服务,因此它不能addscope(将导致错误)。我也尝试了IHttpAccessor,但也不起作用(也给出了一个错误)。如何在控制器依赖项注入中使用HttpContext.sessions?(这是一个很好的做法吗?您可以选择“IHttpContextAccessor” 只需添加启动文件并在控制器中使用它 services.AddScope

在startup.cs中,我有

            services.AddScoped<ISession>();
但是
Isession
不是服务,因此它不能
addscope
(将导致错误)。我也尝试了
IHttpAccessor
,但也不起作用(也给出了一个错误)。如何在控制器依赖项注入中使用HttpContext.sessions?(这是一个很好的做法吗?

您可以选择“IHttpContextAccessor” 只需添加启动文件并在控制器中使用它

 services.AddScoped<IHttpContextAccessor, HttpContextAccessor>();
你的会议

 httpContext.HttpContext.Session

据我所知,如果您想访问当前会话,我们可以在asp.net核心mvc控制器的HttpContext值中直接使用它。不需要自己注入会话。我们只需要在startup.cs中启用会话服务

Asp.net内核将自动调用会话服务,我们可以使用会话方法来获取它

你可以参考下面的资料来了解它是如何工作的

  • 我们应该更新startup.cs ConfigureServices方法并添加以下内容:

         services.AddSession();
    
  • 此AddSession方法是:

    政府的做法如下:

        public async Task Invoke(HttpContext context)
        {
            var isNewSessionKey = false;
            Func<bool> tryEstablishSession = ReturnTrue;
            var cookieValue = context.Request.Cookies[_options.Cookie.Name!];
            var sessionKey = CookieProtection.Unprotect(_dataProtector, cookieValue, _logger);
            if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
            {
                // No valid cookie, new session.
                var guidBytes = new byte[16];
                RandomNumberGenerator.Fill(guidBytes);
                sessionKey = new Guid(guidBytes).ToString();
                cookieValue = CookieProtection.Protect(_dataProtector, sessionKey);
                var establisher = new SessionEstablisher(context, cookieValue, _options);
                tryEstablishSession = establisher.TryEstablishSession;
                isNewSessionKey = true;
            }
    
            var feature = new SessionFeature();
            feature.Session = _sessionStore.Create(sessionKey, _options.IdleTimeout, _options.IOTimeout, tryEstablishSession, isNewSessionKey);
            context.Features.Set<ISessionFeature>(feature);
    
            try
            {
                await _next(context);
            }
            finally
            {
                context.Features.Set<ISessionFeature?>(null);
    
                if (feature.Session != null)
                {
                    try
                    {
                        await feature.Session.CommitAsync();
                    }
                    catch (OperationCanceledException)
                    {
                        _logger.SessionCommitCanceled();
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorClosingTheSession(ex);
                    }
                }
            }
        }
    
    公共异步任务调用(HttpContext上下文)
    {
    var isNewSessionKey=false;
    Func-tryestablishession=ReturnTrue;
    var cookieValue=context.Request.Cookies[_options.Cookie.Name!];
    var sessionKey=CookieProtection.Unprotect(\u dataProtector,cookieValue,\u logger);
    if(string.IsNullOrWhiteSpace(sessionKey)| | sessionKey.Length!=SessionKeyLength)
    {
    //没有有效的cookie,正在创建新会话。
    var guidBytes=新字节[16];
    RandomNumberGenerator.Fill(guidBytes);
    sessionKey=新Guid(guidBytes).ToString();
    cookieValue=CookieProtection.Protect(_dataProtector,sessionKey);
    var-estiblisher=new sessionestiblisher(上下文、cookieValue、_选项);
    tryEstablishSession=建立者.tryEstablishSession;
    isNewSessionKey=true;
    }
    var feature=new SessionFeature();
    feature.Session=_sessionStore.Create(sessionKey、_options.IdleTimeout、_options.IOTimeout、tryEstablishSession、isNewSessionKey);
    context.Features.Set(特征);
    尝试
    {
    等待下一步(上下文);
    }
    最后
    {
    context.Features.Set(null);
    如果(feature.Session!=null)
    {
    尝试
    {
    wait feature.Session.CommitAsync();
    }
    捕获(操作取消异常)
    {
    _logger.SessionCommitCanceled();
    }
    捕获(例外情况除外)
    {
    _记录器错误关闭会话(ex);
    }
    }
    }
    }
    
    您可以找到它读取数据并将其设置到httpcontext中


    所以,需要并且没有内置方式将会话注入控制器。我们可以通过使用
    HttpContext
    直接使用它,或者注入
    IHttpContextAccessor
    并使用它的
    HttpContext

    当前状态下的问题是不完整的,因此不清楚。我解释了所有不清楚的地方?!如何将当前会话放入控制器依赖项注入?这是否回答了您的问题?我收到以下错误
    无法从根提供程序解析作用域服务“Microsoft.AspNetCore.Http.IHttpContextAccessor”。
    @iamaArianme--使用Microsoft.AspNetCore.Http添加
    到文件的顶部。
    
         services.AddSession();
    
        public static IServiceCollection AddSession(this IServiceCollection services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
    
            services.TryAddTransient<ISessionStore, DistributedSessionStore>();
            services.AddDataProtection();
            return services;
        }
    
            app.UseSession();
    
        public async Task Invoke(HttpContext context)
        {
            var isNewSessionKey = false;
            Func<bool> tryEstablishSession = ReturnTrue;
            var cookieValue = context.Request.Cookies[_options.Cookie.Name!];
            var sessionKey = CookieProtection.Unprotect(_dataProtector, cookieValue, _logger);
            if (string.IsNullOrWhiteSpace(sessionKey) || sessionKey.Length != SessionKeyLength)
            {
                // No valid cookie, new session.
                var guidBytes = new byte[16];
                RandomNumberGenerator.Fill(guidBytes);
                sessionKey = new Guid(guidBytes).ToString();
                cookieValue = CookieProtection.Protect(_dataProtector, sessionKey);
                var establisher = new SessionEstablisher(context, cookieValue, _options);
                tryEstablishSession = establisher.TryEstablishSession;
                isNewSessionKey = true;
            }
    
            var feature = new SessionFeature();
            feature.Session = _sessionStore.Create(sessionKey, _options.IdleTimeout, _options.IOTimeout, tryEstablishSession, isNewSessionKey);
            context.Features.Set<ISessionFeature>(feature);
    
            try
            {
                await _next(context);
            }
            finally
            {
                context.Features.Set<ISessionFeature?>(null);
    
                if (feature.Session != null)
                {
                    try
                    {
                        await feature.Session.CommitAsync();
                    }
                    catch (OperationCanceledException)
                    {
                        _logger.SessionCommitCanceled();
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorClosingTheSession(ex);
                    }
                }
            }
        }