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:
- Adding this line to my
Startup.cs
:
app.UseSession();
- Calling
app.UseMvc()
inStartup.cs
isn't required. But I tried using it (just callingapp.UseMvc()
throws an exception. I found the line below in an answer on Stack Overflow after some research):
app.UseMvc(options => options.EnableEndpointRouting = false);
Using
Session.Keys.Contains<string>()
instead ofHttpContext.Session.Keys.Contains<string>()
. But it didn't find a property namedSession
.Surfing the Internet. I didn't find any good answers.
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();