A cookie is a small amount of text added to an HTTP response that the browser includes in later requests. It gives an ASP.NET Core application a way to recognize related requests—for example, to keep a counter or identify an authenticated user. section 16.2
Count visits to an endpoint
In a minimal API endpoint at /cookie, read context.Request.Cookies["counter"] and use "0" when it is absent. Increment the value, then call context.Response.Cookies.Append("counter", value, new CookieOptions { MaxAge = TimeSpan.FromMinutes(30) }). Reload /cookie to see the count rise. A separate /clear endpoint can call context.Response.Cookies.Delete("counter"). Set the cookie before writing the response body: cookies are sent in response headers. section 16.2
CookieOptions controls how a cookie is sent and retained, including its domain, path, expiry, and whether it is marked essential. Basic cookies are not the only way to carry state across requests: sessions provide an alternative for identifying related requests and storing associated data. section 16.2 section 16.0
An authentication cookie has higher stakes than a visit counter. After a successful ASP.NET Core Identity sign-in, the response contains a cookie that identifies subsequent requests as authenticated. Use HTTPS in production: an intercepted authentication cookie could be used to make requests that the application trusts as coming from that user. section 39.2.2 section 39.2.1
Listing 39.5 The Details.cshtml file in the Pages/Account folder of the Advanced folder
@page
@model DetailsModel
<table class="table table-sm table-bordered">
<tbody>
@if (Model.Cookie == null) {
<tr><th class="text-center">No Identity Cookie</th></tr>
} else {
<tr>
<th>Cookie</th>
<td class="text-break">@Model.Cookie</td>
</tr>
}
</tbody>
</table>
@functions {
public class DetailsModel : PageModel {
public string? Cookie { get; set; }
public void OnGet() {
Cookie = Request.Cookies[".AspNetCore.Identity.Application"];
}
}
}
The Razor Page reads .AspNetCore.Identity.Application from Request.Cookies and displays either its value or a message that no Identity cookie is present. It provides a direct way to check the cookie after login and again after logout. section 39.2.2 section 39.2.4
Cookie authentication can also serve a JavaScript web-service client: a successful login response sets the cookie, and the browser includes it in later requests. For /api endpoints, configure cookie authentication to return HTTP errors instead of redirecting unauthenticated clients to a login page. Bearer tokens are another option for web services. section 39.5.3 section 39.5 section 39.6









