0

I am trying to store User Id in Session State like this.

var userInfo = HttpContext.Session.GetString("UserId");

I get an exception on the above line. I have seen the fix for similar problem and most say that I need to call app.UseSession() before app.UseMvc() which I already am. I have no clue how to fix this. I have tried to rearrange the code in Startup.cs but was not able to fix this. Please assist.

InvalidOperationException: Session has not been configured for this application or request

I am storing the user Id like this:

HttpContext.Session.Set("UserId", Encoding.ASCII.GetBytes(user.UserId));

Also, the Current Property is always null so I am not sure if it is storing the UserID correctly. (See Snapshot attached)

enter image description here

I am using ASPNET Core 2.2. Code in the Startup Configure method looks like this

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseSession();
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();

            app.UseMvc();           

        }

In ConfigureServies method, I have added this

   services.AddSession(options => {
                options.IdleTimeout = TimeSpan.FromMinutes(30);

            });
Kiran
  • 19
  • 6

1 Answers1

0

Did you add an implementation of IDistributedCache in `ConfigureServices?

See this doc for a sample implementation:

To enable the session middleware, Startup must contain:

Any of the IDistributedCache memory caches. The IDistributedCache implementation is used as a backing store for session. For more information, see Distributed caching in ASP.NET Core. A call to AddSession in ConfigureServices. A call to UseSession in Configure.

Note that they are using the memory based version of IDistributedCache, which is not actually a distributed cache, but a local one.

LoekD
  • 11,402
  • 17
  • 27