Cookie
Read, write and delete document cookies through a strongly-typed ButilCookie model - no hand-parsing of the document.cookie string, no manually concatenated attribute syntax.
@inject Bit.Butil.Cookie cookieMDN reference
Set writes a ButilCookie to the document. Name and value are percent-encoded automatically (matching encodeURIComponent semantics), so reserved characters and non-ASCII text round-trip safely with values written by JavaScript or the server.
@inject Bit.Butil.Cookie cookie
await cookie.Set(new ButilCookie
{
Name = "theme",
Value = "dark",
});ButilCookie carries every attribute the Set-Cookie syntax supports: Expires, MaxAge, Path, Domain, SameSite, Secure and Partitioned. Expires is emitted in RFC 1123 format; when both Expires and MaxAge are present the browser honors MaxAge.
await cookie.Set(new ButilCookie
{
Name = "session-hint",
Value = "abc123",
MaxAge = 3600, // seconds
Path = "/",
SameSite = SameSite.Strict,
Secure = true,
});
// or with an absolute expiry:
await cookie.Set(new ButilCookie
{
Name = "campaign",
Value = "spring",
Expires = DateTimeOffset.UtcNow.AddDays(7),
});Get returns a single ButilCookie by name, GetValue shortcuts straight to its string value, and GetAll parses every cookie visible to the document. The browser only exposes name=value pairs on read, so attributes such as Path or Expires are never populated on returned cookies.
var theme = await cookie.Get("theme"); // ButilCookie? (Name + Value only)
var value = await cookie.GetValue("theme"); // string?
var all = await cookie.GetAll(); // ButilCookie[]Remove expires the cookie immediately by rewriting it with MaxAge = 0. Pass a name for the common case, or a full ButilCookie when the original was set with a specific Path or Domain - the attributes must match for the browser to delete it.
await cookie.Remove("theme");
// cookie was set with a path? match it on removal:
await cookie.Remove(new ButilCookie { Name = "session-hint", Path = "/" });HttpOnly by the server never appear in document.cookie,
so neither Get nor GetAll can see them. That is by design - it protects
session tokens from script access. Use them for anything security-sensitive.
name=value pairs when reading cookies. A
ButilCookie you get back therefore has default values for Domain,
Expires, MaxAge, Path, SameSite,
Secure and Partitioned - regardless of how it was originally set.
If you need full cookie metadata, use the CookieStore API instead.
API reference
Task<ButilCookie[]> GetAll()Task<ButilCookie?> Get(string name)Task<string?> GetValue(string name)Task Set(ButilCookie cookie)Task Remove(string name)Task Remove(ButilCookie cookie)class ButilCookie { string? Name; string? Value; string? Domain; DateTimeOffset? Expires; long? MaxAge; bool Partitioned; string? Path; SameSite? SameSite; bool Secure; }string ToString()static ButilCookie? Parse(string rawCookie)enum SameSite { None, Lax, Strict }