6 state management techniques for ASP.NET Core MVC


Because HTTP is a stateless protocol, state information is not preserved between requests. This means you must write your own logic to maintain state or find another way to preserve state information.

This article will explore some of the most common state management techniques available in ASP.NET Core MVC and how to use them in your ASP.NET Core MVC applications.

To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 Preview here.

Create an ASP.NET Core MVC project in Visual Studio 2022

First off, let’s create an ASP.NET Core Web API project in Visual Studio 2022. Following these steps will create a new ASP.NET Core Web API project in Visual Studio 2022:

  1. Launch the Visual Studio 2022 Preview IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web App” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  7. Click Next.
  8. In the “Additional Information” window shown next, under Framework, select .NET 7.0.
  9. Leave the check box that says “Use controllers…” unchecked since we’ll be using controllers in this example. Leave the “Authentication Type” set to “None” (default).
  10. Ensure that the check boxes “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we won’t be using any of those features here.
  11. Click Create.

We’ll use this ASP.NET Core 7 Web API project to illustrate state management techniques in the subsequent sections of this article.

Understanding state management

ASP.NET Core MVC provides a rich set of features for building modern web applications, and these include support for a number of ways to manage state. State management is the technique of maintaining the state of an application over time, i.e., for the duration of a user session or across all of the HTTP requests and responses that constitute the session. Thus it is one of the most important cross-cutting concerns of any web application.

In other words, state management is how you keep track of the data moving in and out of your application and how you ensure it’s available when needed. State management allows a smoother user experience by enabling users to pick up where they left off without re-entering their information. Without state management, users would have to enter their information every time they visited or reloaded a new page.

You can manage the state in several ways in an ASP.NET Core MVC application. We’ll examine six ways to handle state in the sections below: cookies, session state, hidden fields, the TempData property, query strings, and caching.

Use cookies to maintain state in ASP.NET Core MVC

A cookie is a piece of data that resides on the user’s computer that helps identify the user. In most web browsers, each cookie is saved in a separate file (the exception is Firefox, which saves all cookies in the same file). Cookies are represented as key-value pairs, and the keys can be used to read, write, or remove cookies. ASP.NET Core MVC uses cookies to preserve session state; the cookie with the session ID is transmitted to the client.

You can use the code snippet given below to write data to a cookie.

CookieOptions options = new CookieOptions();
options.Expires = DateTime.Now.AddSeconds(10);

Use session state to maintain state in ASP.NET Core MVC

Session state is a mechanism for storing user data on the server side in an ASP.NET Core MVC web application. A user’s browser sends the server a request containing information about the user’s session every time the user visits a website. The server then creates a new session and stores the user’s data in that session.

The user’s session and all the user’s data are destroyed when they leave the website. Session state is useful for storing small amounts of data that need to be persisted across multiple requests from a single user. For example, you might use session state to store a user’s shopping cart items or preferences.

The following code snippet illustrates how you can store a key-value pair in the session state in an action method.

public IActionResult Index()
   HttpContext.Session.SetString("MyKey", "MyValue");
   return View();

Use hidden fields to maintain state in ASP.NET Core MVC

When working on ASP.NET Core MVC applications, we may need to preserve data on the client side instead of presenting it on the page. For example, we might need to send data to the server when the user takes a certain action, without showing the data in the user interface. This is a typical problem in many applications, and hidden fields offer an excellent solution. We can store information in hidden form fields and return it in the following request.

The following code snippet illustrates how you can store the user ID of a logged in user and assign the value 1.

@Html.HiddenFor(x => x.UserId, new { Value = "1" })

Use TempData to maintain state in ASP.NET Core MVC

You can use the TempData property in ASP.NET Core to store data until your application reads it. We can examine the data without deleting it using the Keep() and Peek() functions. TempData is extremely helpful when we need data belonging to more than one request. We can get to them using controllers and views.

TempData is used to transmit data from one request to the next, i.e., to redirect data from one page to another. It has a minimal life and only exists until the target view is entirely loaded. However, you may save data in TempData by using the Keep() function. TempData is accessible only during a user’s session. It survives until we read it and then it’s cleared after an HTTP request.

The following code snippet illustrates how you can use TempData in your ASP.NET Core MVC controller.

public class CustomerController : Controller
    public IActionResult TempDataDemo()
        var customerId = TempData["CustomerId"] ?? null;       
        return View();

Use query strings to maintain state in ASP.NET Core MVC

You can take advantage of query strings to transmit a small amount of data from one request to another. Note that because query strings are publicly exposed, you should never use them to pass sensitive data. Additionally, using query strings could make your application vulnerable to cross-site request forgery (CSRF) attacks.

The following code snippet illustrates how you can use query strings in ASP.NET Core MVC.


And, the code snippet below shows how you can read the query string data in your action method.

string region = HttpContext.Request.Query["region"].ToString();

Use caching to maintain state in ASP.NET Core MVC

Caching is yet another way to store state information between requests. You can leverage a cache to store stale data, i.e., data that changes infrequently in your application. ASP.NET Core MVC provides support for three different types of caching, namely in-memory caching, distributed caching, and response caching. The following code snippet shows how you can turn on in-memory caching in your ASP.NET Core MVC applications.


If you would like to store and retrieve instances of complex types in the session state, you can serialize or deserialize your data as appropriate. And if you’d like to send data from your controller to the view, you can take advantage of ViewData.

Copyright © 2022 IDG Communications, Inc.

Leave a Reply