asp.net核心-在Httpcontext.Session上获取system.InvalidOperationException

时间:2019-05-24 05:08:26

标签: c# asp.net-core

我已尝试根据thisthis教程在asp.net核心项目上建立会话。

设置会话的一部分是添加到启动中:

        services.AddDistributedMemoryCache()
        services.AddSession()

并在启动时配置:

        app.UseAuthentication();
        app.UseConfigureSession();  // this..
        app.UseStaticFiles();
        app.UseSession();           // this..
        app.UseMvc(routes =>

现在一切都好,我想在中间件功能中使用它。.

    public async Task InvokeAsync(HttpContext httpContext, IUserSession userSession, ISessionServices sessionServices)
    {
        if (httpContext.User.Identities.Any(id => id.IsAuthenticated))
        {
            if(httpContext.Session.GetString("connectionString") == null) // Session needs to be set..
            {
                userSession.userId = httpContext.User.Claims.FirstOrDefault(x => x.Type == "userId")?.Value;
                userSession.connectionString = sessionServices.ConnectionStringfromUserId(userSession.userId);
                httpContext.Session.SetString("userId", userSession.userId);
                httpContext.Session.SetString("connectionString", userSession.connectionString);
            }
            else  //  Session set so all we need to is to build userSession for data access..
            {
                userSession.userId = httpContext.Session.GetString("userId");
                userSession.connectionString = httpContext.Session.GetString("connectionString");
            }
        }

        // Call the next delegate/middleware in the pipeline
        await _next.Invoke(httpContext);
    }

但是在开始设置Session之前,我发现我正在获取System.InvalidOperationException-请参见下面的图片,其中我使用断点来检查httpContext。

enter image description here

然后在继续操作后消失在乙醚中。

不确定如何解决此问题。不确定导致此问题的设置有什么问题。希望有人能提供一些帮助。

0 个答案:

没有答案