How to Implement HTTP ETags and Conditional Requests in ASP.NET Core 10 Web API
An ETag is a quoted validator for a representation. A browser or API client sends If-None-Match on a GET to avoid downloading an unchanged body. A writer sends If-Match on a PUT to prevent overwriting a revision that changed since it read it.
Read and write preconditions
| Request | Matching current tag | Different tag |
|---|---|---|
| GET with If-None-Match | 304 without a body | 200 with current representation |
| PUT with If-Match | Apply update | 412 Precondition Failed |
| PUT with missing If-Match | 428 in this API | Client must first obtain the validator |
If-Match uses strong comparison. If-None-Match uses weak comparison, so a weak validator with the same opaque value can match on GET. A comma-separated list represents alternatives. A standalone wildcard checks existence in this lab because the resource always exists. Invalid syntax is rejected with 400.
Implement an atomic update
The sample serves a single JSON representation. It locks both the tag check and the write. The response captures an immutable record, so subsequent changes do not mutate a previously selected body. Each write gets a fresh opaque tag. In a database application, put the expected version in the UPDATE predicate and check the affected row count. An application-level check followed by an unconditional UPDATE leaves a race.
Create an empty ASP.NET Core Web project targeting .NET 10, replace Program.cs, then run the app on loopback. Use these commands from the parent directory.
dotnet new web -n Lab -f net10.0
cd Lab
dotnet run --no-launch-profile --urls http://localhost:5080
Program.cs
using Microsoft.Net.Http.Headers;
var app = WebApplication.Create(args);
var gate = new object();
var item = new Item("Original");
var version = Guid.NewGuid();
app.MapGet("/resource", (HttpContext context) =>
{
lock (gate)
{
var tag = new EntityTagHeaderValue($"\"{version:N}\"");
context.Response.GetTypedHeaders().ETag = tag;
context.Response.Headers.CacheControl = "private, no-cache";
if (!TryTags(context.Request.Headers.IfNoneMatch, out var conditions))
return Results.BadRequest();
return Matches(conditions, tag, strong: false)
? Results.StatusCode(304)
: Results.Ok(item);
}
});
app.MapPut("/resource", (HttpContext context, Item update) =>
{
lock (gate)
{
var tag = new EntityTagHeaderValue($"\"{version:N}\"");
if (!context.Request.Headers.ContainsKey("If-Match")) return Results.StatusCode(428);
if (!TryTags(context.Request.Headers.IfMatch, out var matches) ||
!TryTags(context.Request.Headers.IfNoneMatch, out var excludes))
return Results.BadRequest();
if (!Matches(matches, tag, strong: true) || Matches(excludes, tag, strong: false))
return Results.StatusCode(412);
if (string.IsNullOrWhiteSpace(update.Name)) return Results.BadRequest();
item = update;
version = Guid.NewGuid();
return Results.NoContent();
}
});
app.Run();
static bool TryTags(Microsoft.Extensions.Primitives.StringValues raw, out IList<EntityTagHeaderValue>? tags)
{
if (raw.Count == 0) { tags = []; return true; }
return EntityTagHeaderValue.TryParseStrictList(raw.Select(value => value ?? string.Empty).ToArray(), out tags) &&
(tags!.Count == 1 || tags.All(x => x != EntityTagHeaderValue.Any));
}
static bool Matches(IList<EntityTagHeaderValue>? values, EntityTagHeaderValue tag, bool strong)
=> values?.Any(value => value.Equals(EntityTagHeaderValue.Any) || value.Compare(tag, strong)) == true;
record Item(string Name);
Reproduce a lost update safely
- GET /resource and save the ETag, including its quotation marks.
- Send it in If-None-Match with another GET. Expect 304.
- PUT a JSON body such as {“name”:“Updated”} with the original ETag in If-Match. Expect 204.
- Repeat the PUT with that same old value. Expect 412. GET again to inspect the latest state and decide whether to merge the change.
Avoid stripping the W/ prefix before an If-Match comparison. If your API serves different encodings or negotiated representations, design validators for those variants and configure Vary where applicable. For account-specific data, choose cache directives deliberately. The lab uses private, no-cache, which permits private storage but requires validation before reuse. Use no-store where policy requires preventing cache storage.
Common questions
Is an EF Core rowversion automatically a strong HTTP validator? It can participate in one when it changes for every change to the selected representation. A representation assembled from several tables or shaped differently for different clients may need a broader version strategy.
Does a 304 mean the operation failed? It tells a client that made a conditional GET to reuse its existing representation.
Comments
Post a Comment