Home > Blockchain >  Session is not configured. How to fix?
Session is not configured. How to fix?

Time:11-20

I am starting to learn ASP.NET MVC. Now I'm trying to make authentication functionality without using class Membership, class FormsAuthentication, etc. I save the current username into session data.

To check if the user is authenticated I use the following code:

if (!HttpContext.Session.Keys.Contains<string>("authentication")) { // It throws an exception
    return RedirectToAction("Login", "Account");
}

The first line of this snippet throws exception with the following message (my app shows message and target site):

Session is not configured. At "Microsoft.AspNetCore.SessionState.HttpSessionState Microsoft.AspNetCore.HttpContext.get_Session()".

What I have tried:

  1. Adding this line to my Startup.cs:
app.UseSession();
  1. Calling app.UseMvc() in Startup.cs isn't required. But I tried using it (just calling app.UseMvc() throws an exception. I found the line below in an answer on Stack Overflow after some research):
app.UseMvc(options => options.EnableEndpointRouting = false);
  1. Using Session.Keys.Contains<string>() instead of HttpContext.Session.Keys.Contains<string>(). But it didn't find a property named Session.

  2. Surfing the Internet. I didn't find any good answers.

  3. Now I asked my own question.

CodePudding user response:

The problem is solved now. I have added these snippets to Startup.cs:

services.AddControllersWithViews();
services.AddMvc(options => options.EnableEndpointRouting = false).AddSessionStateTempDataProvider();
services.AddSession();

and

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
app.UseMvcWithDefaultRoute();
  • Related