Examples of ASP. NET Core Mvc File Upload restrictions, asp. netmvc
I. Introduction
In ASP. NET Core MVC, the maximum size of files to be uploaded is 20 MB by default. If we want to upload large files, we do not know how to set them. how should we start Config?
Ii. Set the size of the uploaded file
1. application-level settings
Add the following code in the ConfigureServices method to set the file upload size to 60 MB.
public void ConfigureServices(IServiceCollection services){ servicesConfigure<FormOptions>(options => { optionsMultipartBodyLengthLimit = 60000000; });}
2. Action-level settings
In addition to global settings, we can also control a single Action by using a custom 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)); } } }
In ASP. NET Core MVC, unlike previous versions, the specific functions are encapsulated in various Feature (features), and The HttpContext context is only a container that can manage various features. In this Filter, only Action is intercepted and FormFeature (responsible for form submission) in HttpContext is re-set to limit the size of the File Uploaded by a specific Action.
Iii. Conclusion
It seems that a file upload BUG has been found and fixed in version 1.0.1. In version 1.0.0, if Action does not set an IFromFile as the parameter, Request. From. Files cannot be accessed and an exception is reported.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.