首页 > 解决方案 > asp.net Core - Getting a system.InvalidOperationException on Httpcontext.Session

问题描述

I have attempted to set up a session on my asp.net core project as per this and this tutorial(s).

Part of setting up Session was to add into startup:

        services.AddDistributedMemoryCache()
        services.AddSession()

and in startup configure:

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

All good now I wanted to use it in a middleware function..

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

But before I even get to setting Session I found I was getting a System.InvalidOperationException - see pic below where I have used a break point to examine httpContext..

enter image description here

It then disappears into the ether after continuing..

Not sure how to fix this.. not sure what is wrong with the setup to cause this.. hoping someone might shed some light.

标签: c#asp.net-core

解决方案


推荐阅读