NET Centric ComputingUnit 611 min read
State Management in ASP.NET Core: Techniques, Trade-offs & Real-world Use
Unit 6 of NET Centric Computing explores how ASP.NET Core applications maintain user session data, application state, and temporary data across requests. It covers stateless HTTP, client-side vs. server-side state management, cookies, sessions, distributed caching (Redis), temporary data, and performance trade-offs, wi
Why State Management Matters in ASP.NET Core
HTTP is stateless by design: each request is independent. Yet, web apps need to remember user logins, shopping carts, or form inputs. ASP.NET Core provides multiple state management techniques, each with trade-offs in security, scalability, and complexity. This unit teaches you how to choose the right approach for your app.
1. Stateless HTTP: The Core Challenge
How HTTP Works (Statelessness)
sequenceDiagram
participant Client as User (Browser)
participant Server as ASP.NET Core App
Client->>Server: GET /home (Request 1)
Server-->>Client: HTML (No memory of this request)
Client->>Server: POST /login (Request 2)
Server-->>Client: Response (Still no memory)
Note right of Server: Each request is independent- Problem: Without state, the server cannot link Request 2 to Request 1 (e.g., "Is this user logged in?").
- Solutions: Store state client-side (browser) or server-side (database/cache).
Real-world Example: eSewa’s Login Flow
- Scenario: You log in to eSewa, then navigate to "Pay Bill." How does eSewa know you’re logged in?
- Answer: eSewa uses server-side sessions (stored in a database or cache) to track your authentication across requests.
- Why? Client-side cookies alone are vulnerable to XSS attacks (malicious scripts stealing session IDs).
2. Client-Side State Management
A. Cookies
Definition: Small text files stored in the user’s browser, sent with every HTTP request. How it works:
sequenceDiagram
participant Browser
participant Server
Server->>Browser: Set-Cookie: UserID=abc123; Expires=...
Browser->>Server: GET /dashboard (sends Cookie: UserID=abc123)Types of Cookies:
| Type | Description | Security Risk |
|---|---|---|
| Session Cookies | Deleted when browser closes. | XSS (if not HttpOnly) |
| Persistent Cookies | Expires after a set time (e.g., 30 days). | CSRF (if not SameSite) |
| Secure Cookies | Only sent over HTTPS. | Mitigates MITM attacks |
Example: Daraz’s "Remember Me" Feature
- When you check "Remember Me" during login, Daraz sets a persistent cookie with your session ID.
- Trade-off: Cookies are limited to ~4KB and can be stolen via XSS if not secured.
B. Local Storage & Session Storage
- Local Storage: Persists even after browser closure (5MB limit).
- Session Storage: Cleared when the tab closes (same-origin only).
- Use Case: Storing UI preferences (e.g., "Dark Mode") or temporary form data.
- Limitation: Not secure for sensitive data (visible via JavaScript).
Example: Pathao’s Ride History
- Pathao stores your recent rides in
localStorageto show them when you reopen the app. - Why not cookies? Cookies are sent with every request (unnecessary overhead for UI state).
3. Server-Side State Management
A. Sessions
Definition: Server-side storage of user-specific data (e.g., UserId, CartItems) linked to a session ID (stored in a cookie).
How ASP.NET Core Implements Sessions:
// Enable sessions in Program.cs
builder.Services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(30);
options.Cookie.HttpOnly = true; // Prevent XSS
options.Cookie.SecurePolicy = CookieSecurePolicy.Always; // HTTPS only
});
Session Storage Providers:
| Provider | Description | Best For |
|---|---|---|
| In-Memory | Fast but lost if app restarts. | Development only. |
| SQL Server | Persistent, scalable. | Production apps with many users. |
| Redis | Distributed cache (high performance). | Microservices, load-balanced apps. |
Example: Ncell’s User Dashboard
- When you log in to Ncell’s portal, your session is stored in SQL Server.
- Why? Ncell handles millions of users; in-memory sessions would crash under load.
B. Distributed Caching (Redis)
Definition: A high-performance key-value store (e.g., Redis) used for shared session state in load-balanced apps. Why Use Redis?
- Speed: Faster than SQL for session data.
- Scalability: Works across multiple servers.
- Persistence: Data survives app restarts.
Example: Khalti’s Payment Gateway
- Khalti uses Redis to store session data for users across multiple servers.
- Trade-off: Redis is not free (requires infrastructure).
4. Temporary Data (Request-Specific)
Definition: Data needed only for the current HTTP request (e.g., form validation results). How to Use in ASP.NET Core:
// In a controller
public IActionResult SubmitForm()
{
TempData["ErrorMessage"] = "Invalid input!";
return View();
}
Key Points:
- Stored in server memory (cleared after request completes).
- Use Case: Redirects with messages (e.g., "Your order is processing!").
- Limitation: Not persistent across requests.
Example: NEPSE’s Trade Confirmation
- After submitting a trade, NEPSE shows a "Trade submitted!" message using
TempData. - Why? The message is only needed for the next request (then discarded).
5. State Management Trade-offs
| Technique | Persistence | Security Risk | Scalability | Use Case |
|---|---|---|---|---|
| Cookies | Configurable | XSS/CSRF | High | Authentication tokens. |
| LocalStorage | Persistent | None (JS-accessible) | High | UI preferences. |
| Sessions | Configurable | XSS (if cookie) | Medium | User-specific data (cart, profile). |
| Redis | Persistent | Depends on config | Very High | Distributed apps (e.g., Khalti). |
| TempData | Single-request | Low | High | Redirect messages. |
6. Security Best Practices
- Always use
HttpOnlyandSecureflags for cookies:options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = CookieSecurePolicy.Always; - Avoid storing sensitive data in
localStorage(visible via JavaScript). - Use
SameSitecookies to prevent CSRF:options.Cookie.SameSite = SameSiteMode.Strict; - Encrypt session data if using SQL Server or Redis.
Example: Bank of Kathmandu’s Session Security
- Uses encrypted session storage in SQL Server to prevent data leaks.
- Why? Banking apps handle PII (Personally Identifiable Information).
In the Real World
eSewa’s Session Handling
- What it uses: Server-side sessions with Redis for authentication.
- Why? eSewa processes millions of transactions daily; Redis ensures low latency and scalability.
- Security: Sessions are encrypted and expire after inactivity.
Pathao’s Ride Data
- What it uses: LocalStorage for UI state (e.g., saved addresses) and server-side sessions for authentication.
- Why? LocalStorage reduces server load for non-sensitive data.
Ncell’s Load-Balanced Portal
- What it uses: Distributed Redis caching for session state across multiple servers.
- Challenge: Ensuring session consistency when users switch servers.
Worked Example: Building a Shopping Cart in ASP.NET Core
Scenario: A Daraz-like app where users add items to a cart. Solution:
- Store cart in
Session(server-side):// Add to cart HttpContext.Session.SetString("Cart", JsonSerializer.Serialize(cartItems)); // Retrieve cart var cart = JsonSerializer.Deserialize<List<CartItem>>(HttpContext.Session.GetString("Cart")); - Use
TempDatafor flash messages:TempData["SuccessMessage"] = "Item added to cart!"; return RedirectToAction("Cart"); - Security: Enable
HttpOnlyandSecurecookies.
Visualization:
sequenceDiagram
participant User
participant Browser
participant Server
User->>Browser: Clicks "Add to Cart"
Browser->>Server: POST /cart/add
(Cookie: SessionID=xyz789)
Server->>Server: Session["Cart"] += item
Server-->>Browser: RedirectToAction("Cart")
(TempData: "Item added!")
Browser->>Server: GET /cart
(Cookie: SessionID=xyz789)
Server-->>Browser: Renders cart
(with Session["Cart"] data)Exam Tip
- Know the differences:
- Cookies vs. Sessions: Cookies are client-side; sessions are server-side.
- LocalStorage vs. Session Storage: Persistence and scope differ.
- ASP.NET Core configuration:
- How to enable sessions (
AddSession). - How to set
HttpOnly,Secure, andSameSitepolicies.
- How to enable sessions (
- Security questions:
- Why
HttpOnlycookies prevent XSS? - How Redis improves scalability in distributed apps?
- Why
- Common exam scenarios:
- "Design a session management system for a high-traffic app like eSewa."
- "Explain why
TempDatais not suitable for storing user profiles."
- Diagrams:
- Draw the session workflow (cookie → server storage → data retrieval).
- Compare client-side vs. server-side state in a table.
Key Takeaways
- HTTP is stateless; use cookies, sessions, or caching to manage state.
- Client-side storage (cookies, localStorage) is fast but less secure.
- Server-side sessions (SQL/Redis) are scalable but require infrastructure.
- TempData is for short-lived messages (e.g., redirects).
- Security is critical: Always use
HttpOnly,Secure, andSameSitefor cookies. - Real-world apps (eSewa, Khalti, Ncell) use Redis for sessions and encrypted storage for sensitive data.
Based on the TU BIT syllabus for NET Centric Computing (BIT351), unit 6.
Discussion
Loading…