Conquering File Upload Size Limits in ASP.NET Core
ASP.NET Core MVC applications often encounter frustrating file size restrictions. This article provides solutions to handle unlimited file uploads by addressing Kestrel server limitations.
Kestrel's Request Body Size Limits
Kestrel, the web server in ASP.NET Core 2.0 and later, imposes default limits on request body size. To accommodate larger files, configuration adjustments are necessary.
MVC Approach: Attribute-Based Control
The [RequestSizeLimit]
attribute offers granular control over file size limits for specific actions or controllers. For example, this allows the MyAction
method to handle requests up to 100 MB:
<code class="language-csharp">[HttpPost] [RequestSizeLimit(100_000_000)] public IActionResult MyAction([FromBody] MyViewModel data) { }</code>
To remove size restrictions entirely for a specific action or controller, use [DisableRequestSizeLimit]
. This reverts to the behavior prior to ASP.NET Core 2.0.
Middleware Approach: Per-Request Control
For non-MVC requests, the IHttpMaxRequestBodySizeFeature
allows per-request size adjustments:
<code class="language-csharp">app.Run(async context => { context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = 100_000_000; });</code>
Remember: Modifications are only possible if the request body hasn't been read. Check the IsReadOnly
property before making changes.
Global Configuration: Server-Wide Control
To globally adjust the maximum request body size, modify the MaxRequestBodySize
property within the UseKestrel
or UseHttpSys
options:
<code class="language-csharp">.UseKestrel(options => { options.Limits.MaxRequestBodySize = null; // Removes the limit })</code>
or
<code class="language-csharp">.UseHttpSys(options => { options.MaxRequestBodySize = 100_000_000; })</code>
By implementing these configurations, you can effectively eliminate file size limitations in your ASP.NET Core applications, enabling the processing of arbitrarily large uploads.
The above is the detailed content of How to Handle Unlimited File Uploads in ASP.NET Core?. For more information, please follow other related articles on the PHP Chinese website!