Skip to content

HTTP Session ​

Introduction ​

The session keeps the authenticated user and visitor data between requests, like Laravel's: a cart, a chosen language, the time a password was last confirmed. With memory, redis, or database, the browser holds only a protected session id; the data is stored on the server. With cookie, the encrypted, authenticated payload is stored in the browser instead.

Configuration ​

config/Session.cs:

csharp
public class SessionConfig : ConfigFile
{
    public override object Values() => new
    {
        driver = "memory", // memory, redis, database, cookie
        connection = "",   // default database / Redis connection
        table = "sessions",
        lifetime = 120,
        cookie = ".dotblaze.session",
    };
}
Key
drivermemory (default), redis, database, or cookie. Independent of the application cache.
connectionFor database: a connection in database.connections (empty uses database.default). For redis: a connection in database.redis (empty uses default).
tableDatabase session table, default sessions; separate from cache.
prefixRedis key prefix, default session:; appended to the Redis connection's prefix.
lifetimeMinutes of inactivity after which the session expires. Each request that uses the session renews it.
cookieThe cookie name.

The session is loaded the first time a request uses it, and saved before the response is sent. Authentication reads an existing session on each request. A guest without a session cookie causes no session storage I/O.

Drivers ​

  • memory: process-local; sessions are lost on restart and cannot be shared between servers. Suitable for local development and tests.
  • redis: install DotBlaze.Redis, configure the connection in config/Database.cs, and set driver = "redis". Session keys have a sliding TTL and are separate from cache keys. Use the same connection, prefix, and encryption keys on all servers.
  • database: set driver = "database" and run dotblaze migrate. The sample/template includes CreateSessionsTable; existing apps must add this migration. Rows contain id, user_id, ip_address, user_agent, payload, and last_activity. The user_id column is a nullable string to support non-numeric identifiers. Expired rows are rejected on read; a 2% cleanup lottery on writes prunes expired rows.
  • cookie: encrypted and tamper-protected session data lives entirely in the browser. Expiry is checked inside the protected payload. Large cookies are chunked, but browser/proxy header limits still apply; keep session data small. There is no server-side record to delete or revoke: a copied cookie can be replayed after logout until expiry (password changes still invalidate login). Prefer Redis/database when revocation matters.

For existing apps, the database migration is:

csharp
[Migration("2026_11_28_000001_create_sessions_table")]
public class CreateSessionsTable : Migration
{
    public override void Up() => Schema.Create("sessions", t =>
    {
        t.String("id", 40);
        t.Primary("id");
        t.String("user_id").Nullable().Index();
        t.String("ip_address", 45).Nullable();
        t.Text("user_agent").Nullable();
        t.Text("payload");
        t.BigInteger("last_activity").Index();
    });

    public override void Down() => Schema.DropIfExists("sessions");
}

Use the configured database connection for the migration if it differs from the application's default. Treat the session table as sensitive: its payload contains session data, not encrypted application secrets.

Authentication and upgrading ​

Auth.Login stores the user id and password stamp in the session, rotates its id, and preserves other data. Auth.Logout invalidates the session and clears authentication. Deleting a database session row or Redis session key denies subsequent requests with that id. A valid .dotblaze.remember cookie can still create a new login session; revoke the user's remember token too when that is not wanted.

Replace the old session.store setting with session.driver and its connection/table settings. session.store and auth.lifetime no longer control login: session.lifetime controls both auth and session expiry. The old .dotblaze.auth cookie is no longer accepted, and old cache-backed session data is not migrated. Users must log in again unless their remember cookie is still valid. Update custom ASP.NET authentication scheme references from Cookies to Session.

Interacting With the Session ​

The Session facade works in controllers, views, middleware, and live components (it needs an HTTP request). Values are stored as JSON.

Retrieving Data ​

csharp
var count = await Session.Get<int>("cart.count");
var theme = await Session.Get("theme", "light");     // with a fallback
if (await Session.Has("cart.count")) { ... }
var all = await Session.All();                       // every key, as JSON

Storing Data ​

csharp
await Session.Put("cart.count", 3);
await Session.Put("cart", new Cart { Items = items });
await Session.Push("recent.posts", post.Id);         // add to a list
await Session.Increment("visits");
await Session.Decrement("credits", 5);

Deleting Data ​

csharp
await Session.Forget("cart");
await Session.Forget("cart", "theme");
var code = await Session.Pull<string>("login-code");   // read and remove
await Session.Flush();                                 // everything

Regenerating the Session ID ​

Auth.Login gives the visitor a new session id (keeping the data), which prevents session fixation, and Auth.Logout removes the data and starts a new session, like Laravel. To do it yourself:

csharp
await Session.Regenerate();    // new id, same data
await Session.Invalidate();    // new id, no data
var id = await Session.Id();

Flash Data ​

Data for the next request only (a status message after a redirect, validation errors, old input) does not use the session: it is flash data, stored in an encrypted cookie with .With(key, value), see Responses.

Complete Example: Reading Progress ​

Create this controller in a Blog application. It keeps a visitor's selected chapter in the session without requiring a database.

csharp
// app/Http/Controllers/ReadingProgressController.cs
using DotBlaze;
using Microsoft.AspNetCore.Mvc;

namespace Blog.Controllers;

public class ReadingProgressController : BaseController
{
    public async Task<IActionResult> Show() =>
        View(model: await Session.Get("reading.chapter", 1));

    public async Task<IActionResult> Store(int chapter)
    {
        if (chapter is < 1 or > 12)
            return BadRequest(new { message = "Chapter must be between 1 and 12." });
        await Session.Put("reading.chapter", chapter);
        return RedirectRoute("progress.show").With("status", "Progress saved.");
    }
}

Add inside Web.Map():

csharp
Route.Get<Blog.Controllers.ReadingProgressController>("/progress", c => c.Show).Name("progress.show");
Route.Post<Blog.Controllers.ReadingProgressController>("/progress", c => c.Store).Name("progress.store");
html
<!-- resources/views/readingprogress/Show.blade.html -->
@model int
@extends('layouts.app')
@section('content')
    @if (TempData["status"] is string status)
        <p role="status">{{ status }}</p>
    @endif
    <form method="post" action="{{ Route('progress.store') }}">
        @csrf
        <label for="chapter">Current chapter</label>
        <input id="chapter" name="chapter" type="number" min="1" max="12" value="{{ Model }}" />
        <button type="submit">Save</button>
    </form>
@endsection

Run dotblaze serve and visit /progress. Save chapter 4: the redirect displays 4 and the status message. Refresh: 4 remains, while the flash message disappears. A browser without the session cookie defaults to 1. With the template's memory session driver, restarting the server also resets session data; choose Redis or database when that is not desired.