Cookies
Reading and Writing
The Cookie facade uses the current HTTP request and response:
var theme = Cookie.Get("theme", "light");
var present = Cookie.Has("theme");
Cookie.Put("theme", "dark");
Cookie.Forget("theme");Without explicit options, response cookies use HttpOnly, SameSite=Lax, path /, and Secure on HTTPS. Pass ASP.NET Core's CookieOptions to control lifetime, path, domain, and other attributes:
Cookie.Put("theme", "dark", new CookieOptions
{
Path = "/",
HttpOnly = true,
Secure = true,
SameSite = SameSiteMode.Lax,
MaxAge = TimeSpan.FromDays(30),
});These are ordinary cookies; use Crypt if their values need encryption. Match the original path and domain when deleting a cookie. Calls outside an HTTP request fail with a clear error.
Queued Cookies
Cookie.Queue("theme", "dark");
Cookie.QueueForget("obsolete");
return View("settings");Queued cookies are written just before the response headers start, including redirects. The last queued operation for the same name, path, and domain wins. Options are copied when queued. Queue cookies before writing the response body; a response that has already started cannot accept them.
Get and Has read the incoming request, so a new value is visible on the browser's next request.
Complete Example: Theme Preference
In the Blog template, create:
// app/Http/Controllers/ThemeController.cs
using DotBlaze;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Blog.Controllers;
public class ThemeController : BaseController
{
public IActionResult Show() => View(model: Cookie.Get("theme", "light"));
public IActionResult Store(string theme)
{
if (theme is not ("light" or "dark"))
return BadRequest(new { message = "Choose light or dark." });
Cookie.Queue("theme", theme, new CookieOptions
{
Path = "/",
HttpOnly = true,
Secure = Request.IsHttps,
SameSite = SameSiteMode.Lax,
MaxAge = TimeSpan.FromDays(30),
});
return RedirectRoute("theme.show");
}
}Add to Web.Map() in routes/web.cs:
Route.Get<Blog.Controllers.ThemeController>("/theme", c => c.Show).Name("theme.show");
Route.Post<Blog.Controllers.ThemeController>("/theme", c => c.Store).Name("theme.store");<!-- resources/views/theme/Show.blade.html -->
@model string
@extends('layouts.app')
@section('content')
<p>Current theme: {{ Model }}</p>
<form method="post" action="{{ Route('theme.store') }}">
@csrf
<label for="theme">Theme</label>
<select id="theme" name="theme">
<option value="light">Light</option>
<option value="dark">Dark</option>
</select>
<button type="submit">Save preference</button>
</form>
@endsectionRun dotblaze serve, open /theme, and save “Dark”. The redirected GET shows dark; a fresh browser without the cookie shows light. A forged value such as admin gets 400. The cookie is a preference, not an authorization source; clients can modify ordinary cookies. See CookieFacadeTest.cs for browser round-trip assertions.