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. No more How should we start with Web.Config?
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 customize the Filter by A single Action is used for control, and 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, what is different from previous versions is that specific functions are encapsulated in various Among Features, 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 a file upload BUG was discovered, 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.
The above is the entire content of this article. I hope it will be helpful to everyone’s learning, and I also hope everyone will visit the PHP Chinese website.
For more related articles on solving the ASP.NET Core Mvc file upload restriction problem, please pay attention to the PHP Chinese website!