I created a simple ASP.NET Core application (I tried .NET 6 and .NET 8) with a single upload API with a RequestSizeLimitAttribute
.
[HttpPost(Name = "Upload")]
[RequestSizeLimit(100_000)]
public IActionResult Upload()
{
try
{
if (Request.Form.Files.Count != 1)
{
return new BadRequestResult();
}
return new OkResult();
}
catch (BadHttpRequestException ex)
{
if (ex.StatusCode == StatusCodes.Status413PayloadTooLarge)
return new StatusCodeResult(413);
return new StatusCodeResult(500);
}
}
Then I created an application to call that Upload
API method:
HttpClient client = new HttpClient();
using var multiForm = new MultipartFormDataContent();
var fileContent = File.ReadAllBytes("[File Path Here]");
using MemoryStream ms = new MemoryStream(fileContent);
multiForm.Add(new StreamContent(ms), "file", "test.data");
var res = await client.PostAsync("https://localhost:7125/Upload", multiForm);
When I use a file size of 250 kb, everything works fine and the filter works:
StatusCode: 413, ReasonPhrase: 'Payload Too Large', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Connection: close
Date: Tue, 17 Dec 2024 14:32:03 GMT
Server: Kestrel
Transfer-Encoding: chunked
Content-Type: application/problem+json; charset=utf-8
}, Trailing Headers:
{
}
But when I use a larger file (like 15 mb), I get this response:
System.Net.Http.HttpRequestException
HResult=0x80131620
Message=Error while copying content to a stream.
Source=System.Net.HttpStackTrace:
at System.Net.Http.HttpContent.<g__WaitAsync|56_0>d.MoveNext()
at System.Net.Http.MultipartContent.d__24.MoveNext()
at System.Net.Http.HttpContent.<g__WaitAsync|56_0>d.MoveNext()
at System.Net.Http.HttpConnection.d__61.MoveNext()
at System.Net.Http.HttpConnection.d__57.MoveNext()
at System.Net.Http.HttpConnection.d__57.MoveNext()
at System.Net.Http.HttpConnectionPool.d__89.MoveNext()
at System.Threading.Tasks.ValueTask`1.get_Result()
at System.Net.Http.RedirectHandler.d__4.MoveNext()
at System.Net.Http.HttpClient.<g__Core|83_0>d.MoveNext()
at Program.<$>d__0.MoveNext() in C:\Users\pcroc\source\repos\UploadFileTester\UploadFileTester\Program.cs:line 8Inner Exception 1:
IOException: Unable to write data to the transport connection: Connessione in corso interrotta forzatamente dall'host remoto..Inner Exception 2:
SocketException: Connessione in corso interrotta forzatamente dall'host remoto.
Where is the my mistake?
Thank you!
I was able to reproduce your issue on my machine. So the problem is that by default Kestrel has a request body size limit which is around 28mb. You could update it up the max you want to -
builder.WebHost.ConfigureKestrel(serverOptions =>
{
serverOptions.Limits.MaxRequestBodySize = null;
});