Set limits at every layer and fail fast with a clear status. Lower Kestrel's MaxRequestBodySize (default about 28.6 MB) globally, and per endpoint with [RequestSizeLimit]; requests over the limit get 413 Payload Too Large. Set FormOptions limits for multipart. Keep System.Text.Json's MaxDepth (64 by default; lower it for shallow contracts), so deeply nested JSON fails with 400. Validate collection counts in FluentValidation or data annotations and return a ValidationProblem. Stream large uploads instead of buffering, and add rate limiting (AddRateLimiter) so repeated large requests can't exhaust CPU and memory (a denial-of-service vector).
"Oversized and deeply nested payloads are a cheap denial-of-service: one request can make the server allocate hundreds of megabytes or burn CPU walking a nested structure. I put limits at each layer. At the server, Kestrel's
MaxRequestBodySizedefaults to about 28.6 MB, which is far too big for a typical JSON API, so I lower it globally and raise it only on the upload endpoints that need it with[RequestSizeLimit]. Requests over the limit get a 413 before my code runs.For JSON, System.Text.Json already caps depth at 64, and I lower
MaxDepthfor contracts that are only a few levels deep. Size and depth don't stop a body containing 100,000 small items, so I validate collection counts in FluentValidation and return a ValidationProblem with a clear message. For uploads I stream withMultipartReaderstraight to Blob Storage instead of buffering, and setFormOptionslimits. Finally, rate limiting withAddRateLimiter, and body-size rules at Front Door's WAF, stop one client sending big requests in a loop. The mistake I see is raising the global limit to fix one upload endpoint, which exposes every endpoint."
| Layer | Setting | Result when exceeded |
|---|---|---|
| Edge (Front Door WAF, App Gateway) | Max request body size | 413/403 at the edge |
| Kestrel | Limits.MaxRequestBodySize, [RequestSizeLimit] |
413 |
| Forms | FormOptions.MultipartBodyLengthLimit, ValueCountLimit |
400/413 |
| JSON | JsonSerializerOptions.MaxDepth |
400 (JsonException) |
| Validation | Collection count rules | 400 ValidationProblem |
| Throughput | Rate limiter policies | 429 with Retry-After |
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 1_000_000); // 1 MB default
builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.MaxDepth = 16);
public sealed class CreateOrderValidator : AbstractValidator<CreateOrder>
{
public CreateOrderValidator() => RuleFor(x => x.Lines.Count).InclusiveBetween(1, 200);
}
app.MapPost("/documents", UploadAsync).WithMetadata(new RequestSizeLimitAttribute(50_000_000));
Checks practical knowledge of Kestrel, form and JSON limits
Last updated 23 Nov 2026.