dotnet/aspnetcore · error · AntiforgeryValidationException

Unable to read the antiforgery request token from the posted

Error message

Unable to read the antiforgery request token from the posted form.

What it means

Thrown by DefaultAntiforgeryTokenStore.GetRequestTokensAsync (line 64) when ReadFormAsync throws InvalidDataException, indicating the posted form body is malformed (e.g., invalid multipart boundary, malformed encoding). The store wraps it in AntiforgeryValidationException with the original exception as inner, so callers treat it as just another antiforgery failure. This fires only when the request has a form content type, no header token was found, and SuppressReadingTokenFromFormBody is false.

Source

Thrown at src/Antiforgery/src/Internal/DefaultAntiforgeryTokenStore.cs:64

        {
            requestToken = httpContext.Request.Headers[_options.HeaderName];
        }

        // Fall back to reading form instead
        if (requestToken.Count == 0 && httpContext.Request.HasFormContentType && !_options.SuppressReadingTokenFromFormBody)
        {
            // Check the content-type before accessing the form collection to make sure
            // we report errors gracefully.
            IFormCollection form;
            try
            {
                form = await httpContext.Request.ReadFormAsync();
            }
            catch (InvalidDataException ex)
            {
                // ReadFormAsync can throw InvalidDataException if the form content is malformed.
                // Wrap it in an AntiforgeryValidationException and allow the caller to handle it as just another antiforgery failure.
                throw new AntiforgeryValidationException(Resources.AntiforgeryToken_UnableToReadRequest, ex);
            }
            catch (IOException ex)
            {
                // Reading the request body (which happens as part of ReadFromAsync) may throw an exception if a client disconnects.
                // Wrap it in an AntiforgeryValidationException and allow the caller to handle it as just another antiforgery failure.
                throw new AntiforgeryValidationException(Resources.AntiforgeryToken_UnableToReadRequest, ex);
            }

            requestToken = form[_options.FormFieldName];
        }

        return new AntiforgeryTokenSet(requestToken, cookieToken, _options.FormFieldName, _options.HeaderName);
    }

    public void SaveCookieToken(HttpContext httpContext, string token)
    {
        Debug.Assert(httpContext != null);
        Debug.Assert(token != null);

View on GitHub (pinned to 294cab2f9b)

Solutions

  1. Increase form size limits if the upload is legitimately large: builder.Services.Configure<FormOptions>(o => { o.MultipartBodyLengthLimit = long.MaxValue; }).
  2. Inspect the InnerException (InvalidDataException) for the specific form-parse error and message number.
  3. Ensure the client sends a well-formed Content-Type header with a correct boundary for multipart uploads.
  4. If the token should be in the header instead, set AntiforgeryOptions.HeaderName so the form body isn't read at all.

Example fix

// before — default 128MB multipart limit causing InvalidDataException on large uploads
// after — raise the limit
builder.Services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 1_073_741_824; // 1 GB
});
Defensive patterns

Strategy: try-catch

Validate before calling

// Check content length against form limits before validation
if (httpContext.Request.ContentLength
    > builder.Configuration.GetValue<long>("FormOptions:MultipartBodyLengthLimit"))
{
    return BadRequest("Upload too large.");
}

Try / catch

try
{
    await _antiforgery.ValidateRequestAsync(httpContext);
}
catch (AntiforgeryValidationException ex) when (ex.InnerException is InvalidDataException)
{
    _logger.LogWarning(ex, "Malformed form body during antiforgery validation");
    return BadRequest("The submitted form could not be processed.");
}

Prevention

When it happens

Trigger: httpContext.Request.HasFormContentType is true, requestToken from the header is empty, ReadFormAsync() at line 58 throws InvalidDataException. This is a client-side protocol error — the multipart/form-data or urlencoded body violates ASP.NET Core's form parser limits.

Common situations: Multipart form body exceeds MultipartBodyLengthLimit; malformed multipart boundary; URL-encoded body with invalid characters exceeding the form value length limit; a proxy corrupting the request body; a client sending a truncated upload.

Related errors


AI-assisted analysis of dotnet/aspnetcore@294cab2f9b (2026-08-06). Data as JSON: /api/errors/bc3725f461bda88f. Report an issue: GitHub.