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
Also, I need to have replacement for this as well in the .cshtml
file:
var UserName = "@Session["Name"]";
Is there any other method in ASP.NET Core MVC to store or get values on those variables without changing the behavior?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With