Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session in ASP.NET Core MVC

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?

like image 508
user18048414 Avatar asked Oct 17 '25 11:10

user18048414


1 Answers

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); 
  
like image 164
Xinran Shen Avatar answered Oct 19 '25 23:10

Xinran Shen