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?

6
  • 1
    Does this answer your question? How to store and retrieve objects in Session state in ASP.NET Core 2.x? Commented Feb 10, 2022 at 19:41
  • 1
    In addition to the previously asked SO questions, check MSDN Session and state management in ASP.NET Core Commented Feb 11, 2022 at 0:22
  • Is it possible to get and set boolean value from HttpContext.Session. for this condition check if (Convert.ToBoolean(Session["IsSO"]) == true) Commented Feb 11, 2022 at 6:36
  • also for Session["IsSO"] = "false"; Commented Feb 11, 2022 at 6:55
  • Is there any replacement for Session.Clear() in ASP.NET Core MVC? Commented Feb 11, 2022 at 9:38

1 Answer 1

8

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); 
  
Sign up to request clarification or add additional context in comments.

4 Comments

How can we get and set boolean value from HttpContext.Session.
I'm afraid you can't set boolean in HttpContext.Session directly, you can try HttpContext.Session.SetString("A", "true"); bool result = Convert.ToBoolean(HttpContext.Session.GetString("A"));
Thanks. Similarly can we set date as HttpContext.Session.SetString(SessionKeyDate, Start_Date.Date.ToString());
Can you help what can be given for "@Session["Name"]"; in .Net core.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.