How Anti-Forgery Validation Works with File Uploads in .NET 8 Minimal APIs

.NET 8+ automatically validates anti-forgery tokens for multipart file uploads in minimal APIs when UseAntiforgery() is enabled, rejecting requests with missing or invalid tokens via a 400 Bad Request response before the endpoint handler executes.

The dotnet/skills repository hosts the minimal API file upload skill documentation that details this security behavior. According to the source, ASP.NET Core 8 extends the anti-forgery middleware to inspect multipart/form-data requests containing IFormFile parameters, ensuring cookie-based authenticated endpoints remain protected against cross-site request forgery (CSRF) attacks during file uploads.

Automatic Token Validation for Multipart Uploads

When you enable anti-forgery protection in a .NET 8+ application, the middleware automatically intercepts file upload requests. The framework extracts the request verification token from either a hidden form field (__RequestVerificationToken) or the RequestVerificationToken HTTP header and validates it against the cookie-based token before the minimal API endpoint handler receives the IFormFile data.

As documented in the skill specification, this behavior applies to any endpoint receiving form-based file uploads. The validation occurs early in the pipeline, preventing malicious file uploads from reaching your business logic if the CSRF token is absent or mismatched.

Global Middleware Configuration

The UseAntiforgery() extension method registers the middleware that performs this validation globally. According to the implementation details in [SKILL.md](https://github.com/dotnet/skills/blob/main/plugins/dotnet-aspnetcore/skills/minimal-api-file-upload/SKILL.md#L94-L104), this middleware specifically targets multipart content types, ensuring that file uploads receive the same protection as traditional HTML form posts.

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Enable anti-forgery validation for all applicable endpoints
app.UseAntiforgery();

app.MapPost("/upload/profile", async (IFormFile file) =>
{
    // This code only executes if the anti-forgery token is valid
    await using var stream = file.OpenReadStream();
    // Process upload...
    return Results.Ok();
})
.RequireAuthorization(); // Cookie-based auth requires anti-forgery protection

Disabling Validation for API-Only Endpoints

Not all file upload endpoints require anti-forgery protection. API scenarios using JWT Bearer tokens or anonymous access do not need CSRF validation because they do not rely on cookies for authentication. .NET 8+ provides a per-endpoint opt-out mechanism to bypass this validation.

The DisableAntiforgery Extension Method

The DisableAntiforgery() extension method, referenced at [line 231 of SKILL.md](https://github.com/dotnet/skills/blob/main/plugins/dotnet-aspnetcore/skills/minimal-api-file-upload/SKILL.md#L231), instructs the middleware to skip token validation for specific minimal API routes. Only use this method for non-cookie authentication schemes, as disabling anti-forgery on cookie-authenticated endpoints reintroduces CSRF vulnerabilities.

// API-only endpoint with JWT auth - no anti-forgery needed
app.MapPost("/api/upload/public", async (IFormFile file) =>
{
    await using var stream = file.OpenReadStream();
    // Process upload without CSRF token requirement...
    return Results.Ok();
})
.DisableAntiforgery()
.RequireAuthorization("Bearer"); // JWT policy, not cookies

Implementation Architecture

The anti-forgery system in .NET 8+ minimal APIs operates through middleware inspection rather than explicit filters. When UseAntiforgery() is called, the middleware:

  1. Intercepts incoming requests with Content-Type: multipart/form-data
  2. Parses the token from form fields or headers
  3. Validates the token against the anti-forgery cookie
  4. Returns 400 Bad Request immediately if validation fails
  5. Proceeds to the endpoint handler only upon successful validation

This architecture ensures that file uploads cannot bypass security checks through method spoofing or header manipulation, as the validation occurs before route delegation.

Summary

  • Automatic protection: UseAntiforgery() validates CSRF tokens for all multipart/form-data file uploads in minimal APIs without requiring explicit attributes
  • Failure behavior: Invalid or missing tokens result in an immediate 400 Bad Request response before endpoint execution
  • Opt-out mechanism: Use DisableAntiforgery() on specific endpoints that use JWT or other non-cookie authentication schemes to skip validation
  • Security scope: Always maintain anti-forgery protection on cookie-authenticated file upload endpoints to prevent CSRF file upload attacks

Frequently Asked Questions

Does anti-forgery validation apply to all file upload endpoints by default?

Anti-forgery validation only applies when you call UseAntiforgery() in your middleware pipeline and the endpoint accepts IFormFile or IFormFileCollection parameters with multipart/form-data content. Without the middleware, no validation occurs. Endpoints that explicitly call DisableAntiforgery() also bypass validation even when the middleware is present.

How do I disable anti-forgery validation for a specific minimal API endpoint?

Chain the DisableAntiforgery() extension method to your endpoint mapping. This method is available on the route builder and tells the anti-forgery middleware to skip token validation for that specific route. Only disable this for API endpoints using JWT, API keys, or anonymous access—not for cookie-based authentication.

What HTTP response does the client receive when anti-forgery validation fails?

The middleware returns a 400 Bad Request status code immediately when the request verification token is missing, malformed, or does not match the cookie value. This occurs before your endpoint handler executes, preventing any file processing logic from running on potentially malicious requests.

Where should the anti-forgery token be located in file upload requests?

The token can reside in two locations: as a form field named __RequestVerificationToken within the multipart payload (standard for HTML forms), or as an HTTP header named RequestVerificationToken (common for JavaScript fetch/XHR requests). The middleware checks both locations during validation.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →