ASP.NET Core MVC Interview Question #121

What is session state in ASP.NET Core MVC?

Authentication, Authorization, Security & State Management Mid-Level Intermediate

Quick Interview Answer

Session state stores per-user data across multiple HTTP requests using a session identifier, normally held in a cookie. The actual session data is stored by a configured server-side session provider.

Detailed Explanation

Session state stores per-user data across multiple HTTP requests using a session identifier, normally held in a cookie. The actual session data is stored by a configured server-side session provider.

Session is appropriate for small, temporary workflow data but should not become a general-purpose database. In multi-server deployments, use an appropriate distributed session store if session data must be shared between application instances.

Code Example

builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession();

app.UseSession();

HttpContext.Session.SetString(
    "CartId", cartId);