Cookies
suggest changeAn HTTP cookie is a small name/value pair that a server asks the client to store and send back on later requests. The server sets it with a Set-Cookie response header:
Set-Cookie: session=abc123; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax
and the client returns matching cookies in a single Cookie request header:
Cookie: session=abc123; theme=dark
In .NET you deal with cookies in three places:
System.Net.CookieandSystem.Net.CookieContainermodel individual cookies and a client-side "cookie jar"HttpClientuses aCookieContainerto store and send cookies automatically- ASP.NET Core reads cookies from
HttpRequest.Cookiesand writes them withHttpResponse.Cookies
All examples below were run with .NET 10.
1. The Cookie class
System.Net.Cookie holds one cookie together with its attributes:
using System;
using System.Net;
var cookie = new Cookie("theme", "dark", "/", "example.com")
{
Expires = new DateTime(2030, 1, 1, 0, 0, 0, DateTimeKind.Utc),
HttpOnly = true,
Secure = true
};
Console.WriteLine($"Name: {cookie.Name}");
Console.WriteLine($"Value: {cookie.Value}");
Console.WriteLine($"Domain: {cookie.Domain}");
Console.WriteLine($"Path: {cookie.Path}");
Console.WriteLine($"Expires: {cookie.Expires:u}");
Console.WriteLine($"HttpOnly: {cookie.HttpOnly}");
Console.WriteLine($"Secure: {cookie.Secure}");
Console.WriteLine($"Expired: {cookie.Expired}");
Console.WriteLine($"ToString: {cookie}");
// Cookie values can't contain ';' or ',' unencoded
try
{
var bad = new Cookie("list", "a;b");
var c = new CookieContainer();
c.Add(new Uri("https://example.com"), bad);
}
catch (CookieException ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
var ok = new Cookie("list", Uri.EscapeDataString("a;b,c d"));
Console.WriteLine($"Encoded: {ok.Value}");
Console.WriteLine($"Decoded: {Uri.UnescapeDataString(ok.Value)}");
Output:
Name: theme
Value: dark
Domain: example.com
Path: /
Expires: 2030-01-01 00:00:00Z
HttpOnly: True
Secure: True
Expired: False
ToString: theme=dark
Error: The 'Value'='a;b' part of the cookie is invalid.
Encoded: a%3Bb%2Cc%20d
Decoded: a;b,c d
A cookie whose Expires is DateTime.MinValue (the default) is a session cookie: the browser drops it when it closes. Values with spaces, semicolons, commas or non-ASCII characters should be encoded, for example with Uri.EscapeDataString, or Base64Url for binary data.
2. CookieContainer: a cookie jar
CookieContainer stores cookies and applies the browser matching rules: domain, path, Secure and expiration. SetCookies parses raw Set-Cookie header values, and GetCookieHeader builds the Cookie header for a URL:
using System;
using System.Net;
var jar = new CookieContainer();
var site = new Uri("https://shop.example.com/");
// Parse raw Set-Cookie header values, exactly as a server would send them
jar.SetCookies(site, "session=abc123; Path=/; Secure; HttpOnly");
jar.SetCookies(site, "cart=3; Path=/cart");
jar.SetCookies(site, "lang=en; Domain=example.com; Path=/");
// Or add Cookie objects directly
jar.Add(site, new Cookie("currency", "EUR"));
Console.WriteLine($"Count: {jar.Count}");
foreach (var url in new[] {
"https://shop.example.com/",
"https://shop.example.com/cart/items",
"http://shop.example.com/",
"https://blog.example.com/",
"https://other.org/" })
{
string header = jar.GetCookieHeader(new Uri(url));
Console.WriteLine($"{url,-38} -> Cookie: {header}");
}
Console.WriteLine();
foreach (Cookie c in jar.GetCookies(new Uri("https://shop.example.com/cart")))
{
Console.WriteLine($"{c.Name}={c.Value} domain={c.Domain} path={c.Path} secure={c.Secure}");
}
// Delete a cookie by expiring it
foreach (Cookie c in jar.GetCookies(site))
{
if (c.Name == "currency") c.Expired = true;
}
Console.WriteLine();
Console.WriteLine($"After expiring: {jar.GetCookieHeader(site)}");
Output:
Count: 4
https://shop.example.com/ -> Cookie: session=abc123; currency=EUR; lang=en
https://shop.example.com/cart/items -> Cookie: cart=3; session=abc123; currency=EUR; lang=en
http://shop.example.com/ -> Cookie: currency=EUR; lang=en
https://blog.example.com/ -> Cookie: lang=en
https://other.org/ -> Cookie:
cart=3 domain=shop.example.com path=/cart secure=False
session=abc123 domain=shop.example.com path=/ secure=True
currency=EUR domain=shop.example.com path=/ secure=False
lang=en domain=example.com path=/ secure=False
After expiring: session=abc123; lang=en
The output shows the matching rules:
carthasPath=/cart, so it is only sent for/cartand paths below itsessionisSecure, so it is not sent over plainhttp://langhasDomain=example.com, so it is shared with every subdomain- a cookie without a
Domainattribute is "host-only" and goes back only toshop.example.com
3. Cookies with HttpClient
HttpClientHandler (and SocketsHttpHandler) has UseCookies = true by default. Give it a CookieContainer and it stores every Set-Cookie it receives and sends matching cookies on later requests, just like a browser.
This complete program starts a small test server with HttpListener (see HTTP server with HttpListener) and talks to it with HttpClient:
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
const string prefix = "http://localhost:5123/";
// --- A tiny test server built on HttpListener ---
using var listener = new HttpListener();
listener.Prefixes.Add(prefix);
listener.Start();
_ = Task.Run(async () =>
{
while (listener.IsListening)
{
HttpListenerContext ctx;
try { ctx = await listener.GetContextAsync(); } catch { break; }
string body;
switch (ctx.Request.Url!.AbsolutePath)
{
case "/login":
ctx.Response.AppendHeader("Set-Cookie", "session=s3cr3t; Path=/; HttpOnly");
ctx.Response.AppendHeader("Set-Cookie", "user=alice; Path=/; Max-Age=3600");
body = "logged in";
break;
case "/logout":
ctx.Response.AppendHeader("Set-Cookie",
"session=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT");
body = "logged out";
break;
default:
var names = string.Join(", ", ctx.Request.Cookies);
body = $"server saw cookies: [{names}]";
break;
}
byte[] bytes = Encoding.UTF8.GetBytes(body);
ctx.Response.ContentLength64 = bytes.Length;
await ctx.Response.OutputStream.WriteAsync(bytes);
ctx.Response.Close();
}
});
// --- The client: HttpClient with a CookieContainer ---
var cookies = new CookieContainer();
var handler = new HttpClientHandler { CookieContainer = cookies }; // UseCookies is true by default
using var client = new HttpClient(handler) { BaseAddress = new Uri(prefix) };
Console.WriteLine(await client.GetStringAsync("/me"));
Console.WriteLine(await client.GetStringAsync("/login"));
Console.WriteLine(await client.GetStringAsync("/me"));
Console.WriteLine("Jar contents:");
foreach (Cookie c in cookies.GetCookies(new Uri(prefix)))
Console.WriteLine($" {c.Name}={c.Value} HttpOnly={c.HttpOnly} Expires={(c.Expires == DateTime.MinValue ? "session" : "set")}");
Console.WriteLine(await client.GetStringAsync("/logout"));
Console.WriteLine(await client.GetStringAsync("/me"));
// --- Manual mode: no jar, read Set-Cookie and send Cookie yourself ---
using var raw = new HttpClient(new HttpClientHandler { UseCookies = false })
{
BaseAddress = new Uri(prefix)
};
using var resp = await raw.GetAsync("/login");
if (resp.Headers.TryGetValues("Set-Cookie", out var setCookies))
foreach (var sc in setCookies) Console.WriteLine($"Set-Cookie: {sc}");
var req = new HttpRequestMessage(HttpMethod.Get, "/me");
req.Headers.Add("Cookie", "session=manual; debug=1");
using var resp2 = await raw.SendAsync(req);
Console.WriteLine(await resp2.Content.ReadAsStringAsync());
listener.Stop();
Output:
server saw cookies: []
logged in
server saw cookies: [session=s3cr3t, user=alice]
Jar contents:
session=s3cr3t HttpOnly=True Expires=session
user=alice HttpOnly=False Expires=set
logged out
server saw cookies: [user=alice]
Set-Cookie: session=s3cr3t; Path=/; HttpOnly
Set-Cookie: user=alice; Path=/; Max-Age=3600
server saw cookies: [session=manual, debug=1]
Things to know:
- A hand-set
Cookieheader gets merged with the jar whenUseCookiesistrue. In .NET (Core) the handler appends the jar's cookies to your header (manual=1; a=1). To control the header exactly, setUseCookies = false, as in the "manual mode" part above. - With
UseCookies = truethe handler consumesSet-Cookieheaders into the jar. WithUseCookies = falsethey stay inresponse.Headersfor you to read. - A
CookieContainerbelongs to the handler, so every request through thatHttpClientshares one jar. If you need separate sessions (for example, one per user in a scraper), create a separate handler and jar for each. - With
IHttpClientFactory, handlers are pooled and reused across clients, so a shared jar can leak cookies between logical users. Either setUseCookies = falseand manage the header yourself, or configure a handler with its own container viaConfigurePrimaryHttpMessageHandler. See Performing HTTP requests for more aboutHttpClient. HttpListenerResponse.AppendCookie/SetCookiewrite an old-style header that dropsHttpOnlyand joins several cookies with commas. UseAppendHeader("Set-Cookie", ...)with a full value, as above, to get exactly the attributes you want.
4. Saving and restoring a cookie jar
CookieContainer isn't serializable, but since .NET 6 GetAllCookies() returns every cookie it holds. You can write those to JSON and rebuild the jar later, so a command-line tool stays logged in between runs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text.Json;
const string file = "cookies.json";
var jar = new CookieContainer();
var site = new Uri("https://example.com/");
jar.SetCookies(site, "session=abc123; Path=/; Secure; HttpOnly; Max-Age=86400");
jar.SetCookies(site, "theme=dark; Path=/"); // session cookie (no expiry)
jar.SetCookies(site, "old=1; Path=/; Max-Age=0"); // already expired, ignored
CookieJarStore.Save(jar, file);
Console.WriteLine(File.ReadAllText(file));
var restored = CookieJarStore.Load(file);
Console.WriteLine($"Restored: {restored.GetCookieHeader(site)}");
static class CookieJarStore
{
record StoredCookie(string Name, string Value, string Domain, string Path,
DateTime Expires, bool Secure, bool HttpOnly);
static readonly JsonSerializerOptions Options = new() { WriteIndented = true };
public static void Save(CookieContainer jar, string path)
{
var list = jar.GetAllCookies() // .NET 6+
.Where(c => !c.Expired && c.Expires != DateTime.MinValue) // persistent only
.Select(c => new StoredCookie(c.Name, c.Value, c.Domain, c.Path,
c.Expires.ToUniversalTime(), c.Secure, c.HttpOnly))
.ToList();
File.WriteAllText(path, JsonSerializer.Serialize(list, Options));
}
public static CookieContainer Load(string path)
{
var jar = new CookieContainer();
if (!File.Exists(path)) return jar;
var list = JsonSerializer.Deserialize<List<StoredCookie>>(File.ReadAllText(path)) ?? [];
foreach (var s in list.Where(s => s.Expires > DateTime.UtcNow))
{
jar.Add(new Cookie(s.Name, s.Value, s.Path, s.Domain)
{
Expires = s.Expires,
Secure = s.Secure,
HttpOnly = s.HttpOnly
});
}
return jar;
}
}
Output (the timestamp depends on when you run it):
[
{
"Name": "session",
"Value": "abc123",
"Domain": "example.com",
"Path": "/",
"Expires": "2026-10-18T18:29:23.0900666Z",
"Secure": true,
"HttpOnly": true
}
]
Restored: session=abc123
Session cookies (theme) are left out on purpose, the same way a browser forgets them on restart. Cookie files often contain login tokens, so treat them like passwords: store them in a user-only directory and never commit them to source control.
5. Reading and writing cookies in ASP.NET Core
In ASP.NET Core, HttpRequest.Cookies is a read-only IRequestCookieCollection. HttpResponse.Cookies is used to append and delete cookies, and attributes are set with CookieOptions:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/set", (HttpResponse response) =>
{
response.Cookies.Append("theme", "dark", new CookieOptions
{
HttpOnly = true, // not readable from JavaScript
Secure = true, // only sent over HTTPS
SameSite = SameSiteMode.Lax, // not sent on cross-site POSTs
MaxAge = TimeSpan.FromDays(30), // persistent for 30 days
Path = "/"
});
response.Cookies.Append("visits", "1"); // defaults: session cookie, Path=/
return "cookies set";
});
app.MapGet("/get", (HttpRequest request) =>
{
string theme = request.Cookies["theme"] ?? "(none)";
bool hasVisits = request.Cookies.TryGetValue("visits", out var visits);
return $"theme={theme}, visits={(hasVisits ? visits : "(none)")}, total={request.Cookies.Count}";
});
app.MapGet("/clear", (HttpResponse response) =>
{
response.Cookies.Delete("theme", new CookieOptions { Path = "/", Secure = true });
return "theme deleted";
});
app.Run("http://localhost:5124");
Testing with curl:
$ curl -si localhost:5124/set
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Server: Kestrel
Set-Cookie: theme=dark; max-age=2592000; path=/; secure; samesite=lax; httponly
Set-Cookie: visits=1; path=/
cookies set
$ curl -s -H "Cookie: theme=dark; visits=1" localhost:5124/get
theme=dark, visits=1, total=2
$ curl -s localhost:5124/get
theme=(none), visits=(none), total=0
$ curl -si localhost:5124/clear
HTTP/1.1 200 OK
Set-Cookie: theme=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; secure
theme deleted
Delete works by sending the same cookie with an expiration date in the past. The browser only removes it if Path and Domain match the original cookie, so pass the same Path/Domain you used in Append.
6. Cookie authentication
To sign users in, don't invent your own session cookie. The cookie authentication handler stores the user's claims in an encrypted, signed cookie and checks it on every request:
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "__Host-auth"; // __Host- prefix: Secure, Path=/, no Domain
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Lax;
options.ExpireTimeSpan = TimeSpan.FromHours(8);
options.SlidingExpiration = true;
options.LoginPath = "/login";
// For APIs: return 401 instead of redirecting to the login page
options.Events.OnRedirectToLogin = ctx =>
{
ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
return Task.CompletedTask;
};
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapPost("/login", async (HttpContext ctx, string user) =>
{
var claims = new[] { new Claim(ClaimTypes.Name, user), new Claim(ClaimTypes.Role, "admin") };
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await ctx.SignInAsync(new ClaimsPrincipal(identity));
return Results.Ok($"signed in as {user}");
});
app.MapGet("/me", (ClaimsPrincipal user) => $"hello {user.Identity!.Name}")
.RequireAuthorization();
app.MapPost("/logout", async (HttpContext ctx) =>
{
await ctx.SignOutAsync();
return "signed out";
});
app.Run("http://localhost:5124");
Exercising it (the cookie value is shortened):
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:5124/me
401
$ curl -si -X POST "localhost:5124/login?user=alice"
Set-Cookie: __Host-auth=CfDJ8D0l7PKdItBEpIkmR7I84mkJJDfG1xPw...; path=/; secure; samesite=lax; httponly
"signed in as alice"
$ curl -s -H "Cookie: __Host-auth=CfDJ8D0l7PKd..." localhost:5124/me
hello alice
$ curl -si -X POST -H "Cookie: __Host-auth=CfDJ8D0l7PKd..." localhost:5124/logout
Set-Cookie: __Host-auth=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/; secure; samesite=lax; httponly
signed out
By default the auth cookie is a session cookie. Pass new AuthenticationProperties { IsPersistent = true } to SignInAsync to implement "remember me", which makes the cookie last ExpireTimeSpan. For APIs called by non-browser clients, tokens are often a better fit than cookies; see JWT.
7. Tamper-proof cookie values with Data Protection
Anything in a cookie can be read and changed by the client. If you must store a value that the server trusts, such as a cart id or a preference that drives authorization, protect it with ASP.NET Core Data Protection. That is the same mechanism the authentication cookie uses:
using System.Security.Cryptography;
using Microsoft.AspNetCore.DataProtection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDataProtection(); // not registered by default in a bare app
var app = builder.Build();
// A protector is scoped by a "purpose" string; different purposes can't read each other's data
IDataProtector protector = app.Services
.GetRequiredService<IDataProtectionProvider>()
.CreateProtector("Cookies.CartId.v1");
app.MapGet("/cart/new", (HttpResponse response) =>
{
string cartId = Guid.NewGuid().ToString("N")[..8];
response.Cookies.Append("cart", protector.Protect(cartId),
new CookieOptions { HttpOnly = true, SameSite = SameSiteMode.Lax });
return $"new cart {cartId}";
});
app.MapGet("/cart", (HttpRequest request) =>
{
if (request.Cookies["cart"] is not string raw) return "no cart";
try
{
return $"cart {protector.Unprotect(raw)}";
}
catch (CryptographicException)
{
return "cart cookie was tampered with";
}
});
app.Run("http://localhost:5124");
Output when calling /cart/new, then /cart with the original cookie, a modified cookie and a made-up one:
Set-Cookie: cart=CfDJ8D0l7PKdItBEpIkmR7I84mmvBXgOpTQJaCKBdX0z8C3k...; path=/; samesite=lax; httponly
new cart 073bef66
cart 073bef66
cart cookie was tampered with
cart cookie was tampered with
Without AddDataProtection(), GetRequiredService<IDataProtectionProvider>() throws InvalidOperationException: No service for type ... IDataProtectionProvider has been registered. When you run several servers behind a load balancer, they must share the key ring (PersistKeysToFileSystem, Azure Blob Storage, Redis and so on). Otherwise a cookie protected on one machine can't be read on another.
8. Security checklist
| Attribute / practice | Why |
|---|---|
HttpOnly |
JavaScript can't read the cookie, which limits damage from XSS |
Secure |
Never sent over plain HTTP |
SameSite=Lax or Strict |
Not sent on cross-site requests, which mitigates CSRF. SameSite=None requires Secure |
__Host- name prefix |
Browser enforces Secure, Path=/ and no Domain, so subdomains can't overwrite it |
| Short lifetime | Use MaxAge/ExpireTimeSpan. Prefer session cookies for sensitive state |
| Keep it small | Browsers limit a cookie to about 4 KB and cap the number per domain. Every cookie is sent on every matching request |
| Don't trust values | Validate, or protect with Data Protection, anything that the server acts on |
| Never store secrets in plain text | Store an opaque id and keep the data on the server |