Skip to content

Repository files navigation

Soenneker.Blazor.Utils.Cookies

Blazor library for reading, writing, removing, and listing browser cookies. Exposes a low-level ICookiesInterop for direct browser interop and a higher-level ICookiesUtil for app-facing usage.


Install

dotnet add package Soenneker.Blazor.Utils.Cookies

Setup

Register cookie services in Program.cs:

builder.Services.AddCookiesUtilAsScoped();

Inject the higher-level utility in components/services:

@inject ICookiesUtil Cookies

Usage

Get a cookie

string? theme = await Cookies.Get("theme");

Try get a cookie

CookieGetResult result = await Cookies.TryGet("theme");

if (result.Found)
{
    Console.WriteLine(result.Value);
}

Set a cookie

await Cookies.Set("theme", "dark", new CookieOptions
{
    Path = "/",
    MaxAge = TimeSpan.FromDays(30),
    Secure = true,
    SameSite = CookieSameSite.Lax
});

Remove a cookie

await Cookies.Remove("theme");

Read all cookies

IReadOnlyDictionary<string, string> cookies = await Cookies.GetAll();

foreach ((string key, string value) in cookies)
{
    Console.WriteLine($"{key}={value}");
}

Releases

Sponsor this project

Packages

Used by

Contributors

Languages