How to increase request length to upload large files in ASP.NET Core?

11.1k views Asked by At

I have developed an ASP.NET Core Web API which is used to upload files.I am testing the API through postman. When I try to upload file size more than 28 MB it throws request length exceeded error. So I tried to find out solution for this issue. If I increase request length error by changing the value in web.config it works. But my requirement is not to use web.config file. If I increase the MaxRequestBodySize of kestrel server it works fine when I run application through Dotnet CLI but not working when I run application through IIS express from Visual Studio 2019. If I apply [DisableRequestSizeLimit] attribute on POST method it works only on dotnet CLI but not on IIS express. How to increase request length globally for IIS express and Dotnet CLI? Any help is appreciated.

webBuilder.ConfigureKestrel((context, options) =>
                    {
                       
                        options.Limits.MaxRequestBodySize = 524288000;
                    });
2

There are 2 answers

0
Thomas Luijken On

When hosting your webapplication in IIS/IIS Express, configure the web.config file accordingly. See this answer

5
mike On

This is the way to configure it globally without changing the web.config :

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
    .UseStartup<Startup>()
    .UseKestrel(options =>
    {
        options.Limits.MaxRequestBodySize = 524288000;
    });

if not Kestrel :

 .UseHttpSys(options =>
 {
    options.MaxRequestBodySize = 524288000;
 });

OR via middelware

        public void Configure(IApplicationBuilder app )
        {
            app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), appBuilder =>
            {
                context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = null;
            });
        }

if not using UseWhen :

app.Run(async context =>
            {
                context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = 524288000;
            });

OR You could also add header to you controller method :

  [DisableRequestSizeLimit]
  [HttpPost]
  public async Task<IActionResult> Post([FromBody] List<Obj> obj)
  {
  }

//

  [RequestSizeLimit(524288000)]
  [DisableRequestSizeLimit]
  [HttpPost]
   public async Task<IActionResult> Post([FromBody] List<Obj> obj)
   {
   }