Home >Backend Development >C#.Net Tutorial >Example of solving ASP.NET Core Mvc file upload restriction problem
1. Introduction
In ASP.NET Core MVC, the default maximum upload file for file upload is 20MB. If we want to upload some larger files, we don’t know how to set it up. What should we do without Web.Config? Where to start?
2. Set the upload file size
1. Application level settings
We need to add the following code in the ConfigureServices method to set the file upload size limit to 60 MB.
public void ConfigureServices(IServiceCollection services) { servicesConfigure<FormOptions>(options => { optionsMultipartBodyLengthLimit = 60000000; }); }
2.Action level settings
In addition to the global settings above, we can also control a single Action by customizing the Filter. The Filter code is as follows:
[AttributeUsage(AttributeTargetsClass | AttributeTargetsMethod, AllowMultiple = false, Inherited = true)] public class RequestFormSizeLimitAttribute : Attribute, IAuthorizationFilter, IOrderedFilter { private readonly FormOptions _formOptions; public RequestFormSizeLimitAttribute(int valueCountLimit) { _formOptions = new FormOptions() { ValueCountLimit = valueCountLimit }; } public int Order { get; set; } public void OnAuthorization(AuthorizationFilterContext context) { var features = contextHttpContextFeatures; var formFeature = featuresGet<IFormFeature>(); if (formFeature == null || formFeatureForm == null) { // Request form has not been read yet, so set the limits featuresSet<IFormFeature>(new FormFeature(contextHttpContextRequest, _formOptions)); } } }
Because in ASP.NET Core MVC, unlike previous versions, specific functions are encapsulated in various Features, and the HttpContext context is just a container that can manage each feature. In this Filter, only the Action is intercepted, and the FormFeature (responsible for the form submission function) in the HttpContext is reset to achieve the purpose of limiting the size of the file uploaded by the specific Action.
3. Conclusion
It seemed like I found a file upload BUG, but it has been confirmed that it has been fixed in version 1.0.1. In version 1.0.0, if the Action does not set an IFromFile as a parameter, Request.From.Files will not be accessible and an exception will be reported.