Introduction
In ASP.NET Core, you can restrict the uploaded file size using the RequestSizeLimit attribute in the Program.cs file or by configuring it in the appsettings.json file. Additionally, you can set the maximum file size programmatically in your controller actions.
Why do we need to restrict uploaded File Size in an ASP.NET Core?
- Preventing Denial of Service (DoS) Attacks: Allowing unrestricted file uploads can open your application to DoS attacks where malicious users upload excessively large files, consuming server resources and potentially crashing the application or degrading its performance. Limiting file sizes helps mitigate this risk by preventing excessively large uploads.
- Optimizing Server Resources: Large file uploads consume server resources such as memory and disk space. By restricting file sizes, you can better manage these resources, ensuring that your application remains responsive and efficient, especially in shared hosting environments where resource allocation may be limited.
- Ensuring Application Stability: Processing large files can strain server resources and lead to performance issues, timeouts, or crashes. Limiting file sizes helps maintain the stability and reliability of your application by preventing excessive resource consumption during file uploads.
- Improving User Experience: Uploading large files can be time-consuming, especially for users with slow internet connections. Limiting file sizes encourages users to upload smaller, more manageable files, resulting in a faster and smoother user experience.
- Compliance and Regulation: In some cases, regulatory requirements or best practices may dictate maximum file sizes for security or operational reasons. Enforcing file size restrictions helps ensure compliance with such standards and demonstrates a commitment to security and data management practices.
1. Using RequestSizeLimit Attribute
You can use the RequestSizeLimit attribute to restrict the maximum size of the request body, which includes uploaded files.
builder.Services.Configure<FormOptions>(options =>
{
options.ValueCountLimit = int.MaxValue;
options.KeyLengthLimit = int.MaxValue;
options.ValueLengthLimit = int.MaxValue;
options.MultipartBodyLengthLimit = 1000000; // Limit to 1 MB
});
This configuration sets the maximum size of the multipart body to 50 MB.
2. Using appsettings.json
Alternatively, you can configure the maximum request size in the appsettings.json file:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"FormOptions": {
"MultipartBodyLengthLimit": 1000000
}
}
This configuration sets the maximum size of the multipart body to 50 MB.
3. Programmatically in Controller Action
You can also set the maximum file size programmatically in your controller action using the RequestSizeLimit attribute:



Join the conversation! Your thoughts help the community grow.