skip to content

In ASP.NET Core 10 Minimal APIs, why does a form-binding endpoint need AddAntiforgery and UseAntiforgery, and what does DisableAntiforgery change?

level: middleimportance: should knowfreq 46%

answer

  1. form binding implies a token
  2. IAntiforgeryMetadata added by the factory
  3. UseAntiforgery is never added for you
  4. POST, PUT, PATCH only
  5. verdict in IAntiforgeryValidationFeature

basics

~20 s

Since ASP.NET Core 8, a Minimal API parameter bound from a form makes the endpoint require antiforgery. AddAntiforgery registers the services, UseAntiforgery runs the validating middleware (still not automatic in 10), and DisableAntiforgery removes the requirement.

solid answer

~40 s

When `RequestDelegateFactory` sees a `[FromForm]` parameter, an `IFormFile`, an `IFormFileCollection` or an `IFormCollection`, it adds antiforgery metadata with `RequiresValidation = true`. `UseAntiforgery()` adds the middleware that validates such endpoints, and it throws at startup unless `AddAntiforgery()` registered `IAntiforgery`. ASP.NET Core 10's `WebApplication` still does not add `UseAntiforgery` for you; without it, `EndpointMiddleware` throws `InvalidOperationException` because the endpoint has anti-forgery metadata but no middleware ran. The middleware checks only POST, PUT and PATCH, does not short-circuit, and records its verdict in `IAntiforgeryValidationFeature`; form binding then answers `400` (in Development it throws `BadHttpRequestException`). To render the field, call `IAntiforgery.GetAndStoreTokens`. `DisableAntiforgery()` adds metadata with `RequiresValidation = false`, for endpoints no browser form posts to.

code

csharp · 20 lines
csharp
builder.Services.AddAntiforgery();

var app = builder.Build();
app.UseAntiforgery();

app.MapGet("/pledge", (IAntiforgery antiforgery, HttpContext context) =>
{
    var tokens = antiforgery.GetAndStoreTokens(context);
    return Results.Content($"""
        <form method="post" action="/pledge">
          <input type="hidden" name="{tokens.FormFieldName}" value="{tokens.RequestToken}" />
          <input name="amount" /> <button>Pledge</button>
        </form>
        """, "text/html");
});

app.MapPost("/pledge", ([FromForm] decimal amount) => Results.Ok(amount));

app.MapPost("/webhooks/processor", ([FromForm] string eventId) => Results.Ok())
   .DisableAntiforgery();

go deeper

for a junior

Remember that a Minimal API form endpoint needs AddAntiforgery and app.UseAntiforgery, and that DisableAntiforgery opts an endpoint out.

for a middle

Explain which parameters add the metadata, the two exceptions you get when a call is missing, the POST/PUT/PATCH filter, and how form binding turns the recorded verdict into 400.

for a senior

Decide which endpoints may use DisableAntiforgery, add explicit validation for DELETE or JSON endpoints that rely on cookies, and read IAntiforgeryValidationFeature for custom responses.

for a principal

Set a rule for mixed Razor Pages and Minimal API apps on where antiforgery is enforced, and track the .NET 8 to 10 behaviour so upgrades do not silently drop protection.

## What makes a Minimal API endpoint require antiforgery Minimal APIs have no MVC filters, so ASP.NET Core attaches antiforgery as **endpoint metadata**. Since ASP.NET Core 8, when `RequestDelegateFactory` builds an endpoint whose handler binds form data, it adds `IAntiforgeryMetadata` with `RequiresValidation = true`. Form binding means a parameter that is: - marked `[FromForm]`, including a complex type bound from the form; - an `IFormFile` or `IFormFileCollection`; - an `IFormCollection`. A handler that binds JSON, or reads nothing from the body, gets no such metadata and is not checked. `[RequireAntiforgeryToken]` adds the same metadata by hand. ## The three calls and what each one does | Call | Effect | If it is missing | |---|---|---| | `builder.Services.AddAntiforgery()` | registers `IAntiforgery`, `AntiforgeryOptions` and Data Protection | `UseAntiforgery()` throws at startup: "Unable to find the required services..." | | `app.UseAntiforgery()` | adds the antiforgery middleware | a form endpoint throws `InvalidOperationException`: "contains anti-forgery metadata, but a middleware was not found that supports anti-forgery" | | `.DisableAntiforgery()` | adds metadata with `RequiresValidation = false` | the endpoint keeps requiring a token | ASP.NET Core 8's release notes said the builder adds the middleware automatically once the services are registered. In 10.0.12, `WebApplicationBuilder` auto-adds authentication and authorization middleware, never antiforgery. The Blazor Web App template calls `app.UseAntiforgery()` explicitly, and any Minimal API that binds forms must do the same. Where that call sits in the pipeline is covered separately. ## What the middleware does on a request 1. It marks the request as seen, which satisfies the check in `EndpointMiddleware`. 2. If the method is not **POST, PUT or PATCH**, it does nothing more, so a DELETE handler is never validated here. 3. If the endpoint's metadata says `RequiresValidation: true`, it calls `IAntiforgery.ValidateRequestAsync`. 4. It stores the result in **`IAntiforgeryValidationFeature`** (valid, or invalid with the exception) and **always calls the next middleware**. Enforcement happens later, when form binding runs. `RequestDelegateFactory` reads the feature before reading the form; an invalid verdict sets **400 Bad Request**. With `RouteHandlerOptions.ThrowOnBadRequest`, which is `true` in Development, it throws `BadHttpRequestException` ("Invalid anti-forgery token found when reading parameter ...") so the developer exception page shows the cause. ## Issuing the token for a hand-written form Minimal APIs have no tag helper, so the endpoint that renders the form asks `IAntiforgery` for the token set: - `GetAndStoreTokens(context)` writes, or reuses, the antiforgery cookie and returns an `AntiforgeryTokenSet`; - `tokens.FormFieldName` is `__RequestVerificationToken` by default; - `tokens.RequestToken` is the value for the hidden input. ## When `DisableAntiforgery` is right `DisableAntiforgery()` uses `Finally`, so it is applied after other conventions, and it works on a single endpoint or a `MapGroup`. Use it where no browser form with a cookie session can reach the endpoint, for example a form-encoded webhook from a payment processor that you verify by signature. It is not a fix for the missing-middleware exception: that exception means a browser form endpoint has no validator, and the fix is `app.UseAntiforgery()`. ## Razor Pages and Minimal APIs in one app The charity's site has a Razor Pages donation form and a Minimal API `/pledge` endpoint side by side. The two mechanisms do not overlap: - Razor Pages endpoints carry no `IAntiforgeryMetadata` by default, so `AntiforgeryMiddleware` skips them, and the page's own `AutoValidateAntiforgeryToken` filter checks them. - The Minimal API endpoint carries the metadata, so only the middleware checks it. - `AddRazorPages()` already registers the antiforgery services, so `AddAntiforgery()` is redundant in such an app, but harmless: every registration uses `TryAdd`. - What is never implied by `AddRazorPages()` is the middleware. Forgetting `app.UseAntiforgery()` leaves the pages working and makes only the Minimal API form endpoint throw, which is why the failure often first appears in production on the least-used endpoint.

  • In an ASP.NET Core Minimal API, how can a handler see why antiforgery validation failed instead of getting a bare 400?
    The middleware records its result in `IAntiforgeryValidationFeature`, whose `IsValid` and `Error` properties carry the outcome and the `AntiforgeryValidationException`. Mark the endpoint `[RequireAntiforgeryToken]` (or `WithMetadata(new RequireAntiforgeryTokenAttribute())`) and do not bind form parameters, for example by reading `HttpContext.Request.Form` yourself; then the handler runs and can read `context.Features.Get<IAntiforgeryValidationFeature>()`. Form-bound parameters short-circuit with 400 first.
  • Why is a DELETE endpoint marked [RequireAntiforgeryToken] in an ASP.NET Core Minimal API not validated by UseAntiforgery?
    `AntiforgeryMiddleware` validates only methods that can carry a form body, POST, PUT and PATCH, and lets every other method through without calling `IAntiforgery`. A cookie-authenticated DELETE needs another defence, such as calling `IAntiforgery.ValidateRequestAsync` explicitly in the handler or an endpoint filter.

  • WebApplication adds UseAntiforgery automatically once AddAntiforgery is registered.
  • A Minimal API endpoint that binds JSON is validated by UseAntiforgery too.
  • The antiforgery middleware returns 400 itself before the endpoint runs.
  • DisableAntiforgery() is the right fix for the missing-antiforgery-middleware exception on a browser form.
  • UseAntiforgery validates DELETE requests the same way as POST.

Assumes ASP.NET Core 10; Minimal API form binding has required antiforgery since 8, and in 10 WebApplication still does not insert UseAntiforgery.