The name 'Session' does not exist in the current context

By FoxLearn 6/13/2024 8:34:39 AM   49
How to fix 'The name 'Session' does not exist in the current context' in ASP.NET Core.

If you migrate an ASP.NET MVC application to ASP.NET Core MVC.

In ASP.NET MVC, you using some Session variables to store or get values like this

Session["UserId"] = user.Id;
string id = Session["UserId"];

After you convert and get the following error:

The name 'Session' does not exist in the current context

If you're encountering the "The name 'Session' does not exist in the current context" error in ASP.NET Core, it's likely because the Session object is not available in the current scope.

Here are some potential reasons and solutions:

You need to add session middleware in your configuration file by opening your Startup.cs file, within the ConfigureServices method, add the following code to enable session state:

public void ConfigureServices(IServiceCollection services)  
{  
    // Configure session options here
    services.AddSession(options => {  
        options.IdleTimeout = TimeSpan.FromMinutes(30);
    });
} 

Next, In the Configure method of the Startup.cs file, add the following code to enable the session middleware:

app.UseSession();

Now you should be able to access the Session object within your controllers.

public class YourController : Controller
{
    public IActionResult Index()
    {
        // set session
        HttpContext.Session.SetString("UserId", "foxlearn");
        // get session
        var userId = HttpContext.Session.GetString("UserId");
        return View();
    }
}

You should have a reference to Microsoft.AspNetCore.Session package. Ensure that the app.UseSession() call is placed after the app.UseRouting() call in your Configure method in Startup.cs.