I am migrating an ASP.NET MVC application to ASP.NET Core MVC.
In ASP.NET MVC, I am using some Session
variables to store or get values like:
Session["UserID"] = user.UserName;
Session["Role"] = role[0].ROLE_DESCRIPTION;
ViewData["LEVEL"] = Session["LEVEL"];
But after converting, I get an error:
The name 'Session' does not exist in the current context
Is there any other method in ASP.NET Core MVC to store or get values on those variables without changing the behavior?
CodePudding user response:
You need to add session middleware in your configuration file
public void ConfigureServices(IServiceCollection services)
{
//........
services.AddDistributedMemoryCache();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(1);//You can set Time
});
services.AddMvc();
}
public void ConfigureServices(IServiceCollection services)
{
//......
app.UseSession();
//......
}
Then in your controller, you can
//set session
HttpContext.Session.SetString(SessionName, "Jarvik");
HttpContext.Session.SetInt32(SessionAge, 24);
//get session
ViewBag.Name = HttpContext.Session.GetString(SessionName);
ViewBag.Age = HttpContext.Session.GetInt32(SessionAge);