---
title: "How to enable Session in ASP.NET Core?"  
description: "How to enable Session in ASP.NET Core?"  
author: "Sanjay Goenka"  
published: 2023-03-06  
updated: 2023-07-07  
canonical: https://www.mindstick.com/forum/157460/how-to-enable-session-in-asp-dot-net-core  
category: "asp.net core"  
tags: ["asp.net", "asp.net core"]  
reading_time: 2 minutes  

---

# How to enable Session in ASP.NET Core?

How to enable [Session](https://www.mindstick.com/articles/12042/session-in-c-sharp) in [ASP.NET Core](https://www.mindstick.com/articles/12946/get-started-with-asp-dot-net-core-mvc-and-visual-studio)?

## Replies

### Reply by Aryan Kumar

I apologize, but I'm unable to access external websites or open specific URLs. However, I can provide you with information on how to enable sessions in [ASP.NET](https://www.mindstick.com/articles/934/default-folders-available-inside-the-asp-dot-net-application-folder) Core.

To enable session state in ASP.NET Core, you need to follow these steps:

1. First, make sure you have the necessary dependencies installed. In your ASP.NET Core project, open the `Startup.cs` file.

2. In the `ConfigureServices` method, add the following code to enable session state:

```plaintext
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
   options.IdleTimeout = TimeSpan.FromMinutes(30); // Set the session timeout value as per your requirement
   options.Cookie.HttpOnly = true;
   options.Cookie.IsEssential = true;
});
```

Here, we're using the `DistributedMemoryCache` as the session state store. You can also use other distributed cache providers like Redis or SQL Server.

3. Next, in the `Configure` method of `Startup.cs`, add the following code to enable session state middleware:

```plaintext
app.UseSession();
```

Make sure you place this line before any middleware that depends on session state.

4. Now, you can use the session in your controllers or views. For example, in a controller, you can set a session value as follows:

```plaintext
public IActionResult SetSession()
{
   HttpContext.Session.SetString("UserName", "John");
   return RedirectToAction("Index");
}
```

And to retrieve the session value:

```plaintext
public IActionResult GetSession()
{
   var userName = HttpContext.Session.GetString("UserName");
   return View(userName);
}
```

Remember to add the `using Microsoft.AspNetCore.Http;` namespace in your controller.

That's it! You have now enabled session state in ASP.NET Core. The session values will be stored in the configured session store (in this case, the distributed memory cache) and can be accessed throughout the user's session.


---

Original Source: https://www.mindstick.com/forum/157460/how-to-enable-session-in-asp-dot-net-core

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
