C# tutorials > Frameworks and Libraries > ASP.NET Core > How to handle state management in ASP.NET Core?
How to handle state management in ASP.NET Core?
State management is crucial in ASP.NET Core web applications to maintain information across multiple requests. Several mechanisms are available, each suited for different scenarios. This tutorial explores various options for managing state, including TempData, Session, Cookies, and hidden form fields.
Introduction to State Management in ASP.NET Core
Using TempData for Short-Lived Data
Index
action and retrieved in the About
action. Once accessed, the data in TempData is automatically marked for deletion.
public class HomeController : Controller
{
public IActionResult Index()
{
TempData["Message"] = "Welcome to ASP.NET Core!";
return RedirectToAction("About");
}
public IActionResult About()
{
ViewBag.Message = TempData["Message"] as string;
return View();
}
}
Concepts behind TempData
Real-Life Use Case for TempData
Utilizing Session State for User-Specific Data
Startup.cs
:services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
app.UseSession();
IHttpContextAccessor
to access the current HTTP context and then set and retrieve the UserName
from the session. Remember to configure session services in your Startup.cs
file.
public class HomeController : Controller
{
private readonly IHttpContextAccessor _httpContextAccessor;
public HomeController(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public IActionResult Index()
{
_httpContextAccessor.HttpContext.Session.SetString("UserName", "JohnDoe");
return View();
}
public IActionResult About()
{
var userName = _httpContextAccessor.HttpContext.Session.GetString("UserName");
ViewBag.UserName = userName;
return View();
}
}
Concepts behind Session State
Real-Life Use Case for Session State
Working with Cookies for Client-Side Storage
Theme
is set with a value of Dark
and an expiration date. The About
action retrieves the cookie value and uses it to set the theme.
public class HomeController : Controller
{
public IActionResult Index()
{
Response.Cookies.Append("Theme", "Dark", new CookieOptions { Expires = DateTimeOffset.Now.AddDays(30) });
return View();
}
public IActionResult About()
{
if (Request.Cookies.TryGetValue("Theme", out string theme))
{
ViewBag.Theme = theme;
}
else
{
ViewBag.Theme = "Light";
}
return View();
}
}
Concepts behind Cookies
Real-Life Use Case for Cookies
Leveraging Hidden Form Fields for Maintaining State Within a Form
ProductId
is stored in a hidden field and submitted along with the Quantity
when the form is submitted.
<form asp-action="SubmitForm" method="post">
<input type="hidden" name="ProductId" value="123" />
<input type="text" name="Quantity" />
<button type="submit">Submit</button>
</form>
public IActionResult SubmitForm(int ProductId, int Quantity)
{
// Process the form data
return View();
}
Concepts behind Hidden Form Fields
Real-Life Use Case for Hidden Form Fields
Best Practices for State Management
Interview Tip
When to use them
Memory footprint
Alternatives
Pros and Cons
Session:
Cookies:
Hidden Form Fields:
FAQ
-
How do I enable Session state in ASP.NET Core?
To enable Session state, you need to configure it inStartup.cs
. First, add the Session services to the container withservices.AddSession()
. Then, add the Session middleware withapp.UseSession()
. Ensure thatapp.UseSession()
is placed afterapp.UseRouting()
and beforeapp.UseEndpoints()
. You might also need to add a distributed cache implementation like Redis. -
How do I encrypt data stored in cookies?
To encrypt data stored in cookies, you can use data protection APIs provided by ASP.NET Core. These APIs allow you to encrypt and decrypt data using a key management system. You can useIDataProtector
to encrypt the cookie value before storing it and decrypt it when retrieving it. -
What is the difference between session cookies and persistent cookies?
Session cookies are temporary cookies that are deleted when the browser is closed. Persistent cookies, on the other hand, have an expiration date and are stored on the client's hard drive until they expire or are manually deleted. Session cookies are typically used for maintaining session state, while persistent cookies are used for remembering user preferences or tracking user activity over time.