4

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?

user18048414
  • 161
  • 2
  • 15
  • 1
    Does this answer your question? [How to store and retrieve objects in Session state in ASP.NET Core 2.x?](https://stackoverflow.com/questions/55220812/how-to-store-and-retrieve-objects-in-session-state-in-asp-net-core-2-x) – Rajesh G Feb 10 '22 at 19:41
  • 1
    In addition to the previously asked SO questions, check MSDN [Session and state management in ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-6.0) – Metro Smurf Feb 11 '22 at 00:22
  • Is it possible to get and set boolean value from `HttpContext.Session.` for this condition check `if (Convert.ToBoolean(Session["IsSO"]) == true)` – user18048414 Feb 11 '22 at 06:36
  • also for `Session["IsSO"] = "false";` – user18048414 Feb 11 '22 at 06:55
  • Is there any replacement for `Session.Clear()` in ASP.NET Core MVC? – user18048414 Feb 11 '22 at 09:38
  • session working example: https://www.aspsnippets.com/questions/770188/Using-Set-or-Get-Session-in-ASPNet-Core-MVC/ – Billu Oct 17 '22 at 08:41

1 Answers1

7

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); 
  
Xinran Shen
  • 8,416
  • 2
  • 3
  • 12