State management in ASP.NET Core

 

ASP.NET Core state management maintains and shares data across multiple user requests in a web application. Since HTTP is stateless, ASP.NET Core offers numerous ways to save data between requests. The state management approach you choose relies on data sensitivity, size, longevity, and application performance. 

 

Client-Side State Management:

  • These methods store state directly on the client's browser.
    • Query Strings:
      • Data is appended to the URL as name-value pairs. Suitable for small, non-sensitive data like page numbers, sorting parameters, or simple identifiers.
      • Pros: Simple to implement, data is visible and can be easily shared via links.
      • Cons: Limited data size, visible data in URL (security risk for sensitive information), might make URLs unreadable.
    • Hidden Fields:
      • Data is stored in <input type="hidden" ...> elements within an HTML form. When the form is submitted, these values are sent to the server. Useful for maintaining state related to a specific form across multiple submissions.
      • Pros: Simple to implement for form-related data.. 
      • Cons: Data is visible in the page source (potential security risk), limited to form submissions.
    • Cookies:
      • Small text files that the server sends to the client's browser, and the browser sends back with subsequent requests to the same domain.
      • Used for saving user preferences, session identifiers, shopping cart contents (briefly), and activity tracking
      • Pros: Easy to use, persistent between browser sessions (may be specified with an expiration date). 
      • Cons: Limited data size (usually 4KB per cookie), can be disabled by the user, data is sent with every request (potential overhead), less suitable for large or complex data.
      •  
    • Local Storage and Session Storage (Browser Storage):
      • Modern browsers have Web Storage APIs that let you save data on the client side. Good for keeping user preferences, offline data, or information that is only needed for a short time on the client. Usually, you use JavaScript to work with these.
        • Local Storage: Data stays the same even when you close the browser 
        • Sessions: The data is only available for the current browser session, and it is deleted when the tab or window is closed.
        • Pros: Less overhead than cookies, larger storage capacity (usually several megabytes), and data is not automatically delivered with every request. 
        • Cons: Client-side data can be changed by users (security risk for sensitive data), not available across browsers on the same machine.

Server-Side State Management:

  • Session
    • Allows storing user-specific data across many browser queries. A session identifier (typically kept in a cookie) links requests to a server session in ASP.NET Core. Ideal for storing user-specific information like shopping cart contents, user authentication status, temporary messages, and user preferences that need to persist across a session.
    • Storage Options:
      • In-Memory: Data is saved in the web server's memory.  Simple to configure but not suitable for load-balanced environments (data is lost if a server goes down).
      • Distribution Cache (Redis, SQL Server, etc.): Data is stored in an external cache that can be shared across multiple servers in a web farm. This method is suggested for production.
    •  
  • TempData:
    • A temporary mechanism to transmit data between requests, usually after a redirect. TempData data is normally erased after reading. It usually stores data in cookies or sessions.
    • Primarily used for "flash messages" or status updates after an operation.
    • Pros: Displays success or error messages following form submission and redirect, preventing data reuse. 
    • Cons: Only for one-time data transfer between actions.
    •  
  • Caching:
    • To speed up applications, stores often kept data in memory or a distributed cache so that they didn't have to get it from the original source (like a database) every time they needed it. Caching is employed to store data that is frequently accessed and does not undergo frequent changes, such as product catalogues, configuration settings, or the outcomes of costly computations. Although its primary purpose is to enhance performance, it can also be employed to preserve specific application-wide states.
    • Types:
      • IMemoryCache, or In-Memory Cache, keeps data in the memory of the web server so that it can be accessed more quickly. Good for situations with only one server.
      • Distributed Cache (IDistributedCache - Redis, SQL Server, etc.): This type of cache is shared by more than one server, which makes it easier to scale and makes it more reliable.
      • Response Caching: Stores the whole HTTP response on the server or client to lighten the burden on the server.
    • Pros: Increased performance, reduced backend load. 
    • Cons: Data must be managed carefully to avoid staleness.
    •  
  • Application State:
    • Stores application-wide data for all users and sessions. This is usually done with static variables or singleton services. For global program settings, counters, or read-only reference data that all users share. Use with caution for mutable data due to concurrency concerns.
    • Pros: Simple to implement for application-wide data. 
    • Cons: All users share data (possible concurrency concerns if not managed correctly), data is lost when the application restarts.
  • Database:
    • Stores application data in a relational database (like SQL Server or PostgreSQL) or a NoSQL database (like MongoDB or Cosmos DB) all the time.
    • The main way to store long-term application data, such as user accounts, business entities, and information that is specific to the application.
    • Pros: It works well, can grow with your needs, can handle complicated data linkages, and data stays the same over program restarts and user sessions.
    • Cons: It can be slower than in-memory choices and needs to be set up and managed in a database.


 


Session Vs Cache

  • Purpose: Primarily used to store data that is specific to a single user's session while they are interacting with the web application. It allows you to maintain state across multiple requests from the same user. Think of it as a temporary, private storage area for each user.
    Scope: Per user, per browser session. Data stored in a session is generally not accessible to other users or across different browser sessions for the same user (unless cookies are configured to persist).
  • Lifespan: Typically tied to the user's active session. It has a timeout period (e.g., 20 minutes of inactivity by default), after which the session data is usually discarded. Session can also be explicitly cleared
  • Data Sensitivity: Suitable for storing user-specific information like shopping cart contents, authentication status, user preferences, and temporary messages. It's generally more secure for user-specific data than client-side storage.

 

 

  • Purpose: Primarily used to store frequently accessed data that is relatively static or doesn't change often, to improve application performance by reducing the need to repeatedly retrieve it from the original source (like a database or external API). It's about making the application faster and more responsive for all users.
  • Scope: Application-wide and shared across all users and sessions. Data stored in the cache is generally the same for everyone.
  • Lifespan: Managed based on various policies, such as:
    • Absolute Expiration: Data expires after a specific point in time.
    • Sliding Expiration: Data expires if it's not accessed within a certain time period.
    • Cache Dependencies: Data can be invalidated when its underlying source changes.
    • Manual removal.
  • Data Sensitivity: Suitable for storing data that is not user-specific and can be shared, such as product catalogs, configuration settings, results of expensive computations, or frequently read database queries. Be cautious about caching sensitive user-specific data unless properly handled.

Related Question