Example of solving ASP. NET Core Mvc file upload restriction problem

  • 2021-08-28 19:54:03
  • OfStack

1. Introduction

In ASP. NET Core MVC, the maximum uploaded file is 20MB by default. If we want to upload a larger file, we don't know how to set it. How should we start without Web. Config?

2. Set the upload file size

1. Application-level settings

We need to add the following code to 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 setting

In addition to setting the global situation above, we can also control a single Action by customizing Filter. The code of Filter 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, different from previous versions, specific functions are encapsulated in various Feature (features), and HttpContext context is only a container that can manage various features. In this Filter, only Action is intercepted, and FormFeature (responsible for form submission function) in HttpContext is reset, so as to limit the uploaded file size of specific Action.

3. Conclusion

Originally, it felt like an BUG file upload was found, and it has been confirmed that it has been fixed in version 1.0. 1. In version 1.0. 0, Request. From. Files will not be accessible and an exception will be reported if Action does not set 1 IFromFile as a parameter.


Related articles: