dotnet / dotnet/aspnetcore

Kestrel returns 400 status code when request size is greater than MaxRequestBodySize

Open
#49,365 9 comments 0 reactions 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

When uploading a file larger than a default limit (30000000 bytes) Kestrel returns 400 status code, instead of 413.

Seems like similar issue have been already proposed https://github.com/dotnet/aspnetcore/issues/47525

### Expected Behavior

I expect 413 status code in this case.

[`Http1ContentLengthMessageBody.OnReadStarting`](https://github.com/dotnet/aspnetcore/blob/d194f5091ffa2ebd450845edf30721d623d848dd/src/Servers/Kestrel/Core/src/Internal/Http/Http1ContentLengthMessageBody.cs#L244) throws [`new BadHttpRequestException(CoreStrings.FormatBadRequest_RequestBodyTooLarge(detail), StatusCodes.Status413PayloadTooLarge, reason);`](https://github.com/dotnet/aspnetcore/blob/d194f5091ffa2ebd450845edf30721d623d848dd/src/Servers/Kestrel/Core/src/KestrelBadHttpRequestException.cs#L143) when body size is greater setting 413 status code.

Then [`HttpProtocol.ProcessRequestsAsync`](https://github.com/dotnet/aspnetcore/blob/d194f5091ffa2ebd450845edf30721d623d848dd/src/Servers/Kestrel/Core/src/Internal/Http/HttpProtocol.cs#L569) catches this exception calling [`HttpProtocol.SetBadRequestState`](https://github.com/dotnet/aspnetcore/blob/d194f5091ffa2ebd450845edf30721d623d848dd/src/Servers/Kestrel/Core/src/Internal/Http/HttpProtocol.cs#L1398). And at this moment `HttpProtocol.HasResponseStarted == true` what prevents setting status code from exception.

For me it's seems a bit confusing

### Steps To Reproduce

Try to upload a file larger than 30MB

### Exceptions (if any)

_No response_

### .NET Version

.NET 7, .NET 8 Preview 6

### Anything else?

Tested with ASP.NET Core 7, ASP.NET Core Runtime 8.0.0-preview.6

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.