3

I am creating a file upload with .NET Core 3.1.

When I uploaded a file larger than 100 MB, I got an error:

413 Request Entity Too Large

As a result of various investigations, I was able to avoid the 413 error by making the following settings:

web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <security>
        <requestFiltering>
          <!-- Handle requests up to 1 GB -->
          <requestLimits maxAllowedContentLength="1073741824" />
        </requestFiltering>
      </security>
    </system.webServer>
  </location>
</configuration>

UploadController.cs:

        [Route("embed")]
        [HttpPost]
        [DisableRequestSizeLimit]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        public ActionResult PostEmbed([FromForm] WebPptVoiceEmbedRequest request)
        {
            Log.NLog.Debug("[Get]:PostEmbed start");

            byte[] array;
            using (var stream = new MemoryStream())
            {
                request.File.CopyTo(stream);
                array = stream.ToArray();
            }

            Log.NLog.Debug("[Get]:PostEmbed end");
            
            return File(array, "application/vnd.openxmlformats-officedocument.presentationml.presentation", request.File.FileName);
        }

Program.cs:

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.ConfigureKestrel(options =>
                    {
                        options.Limits.MaxRequestBodySize = null;
                    })
                    .UseStartup<Startup>();
                })
                .ConfigureLogging(logging =>
                {
                    logging.ClearProviders();
                    logging.SetMinimumLevel(LogLevel.Debug);
                })
                .UseNLog();

client.js

  let embedRequest = new FormData();
  embedRequest.append('file', file);

    const { data } = await axios
      .post(Api.embed, embedRequest, {
        responseType: 'blob',
        dataType: 'binary',
      })
      .catch((error) => {
        apiErrorLogAndThrow(error);
      });
    const blob = new Blob([data]);
    return blob;

However, I still get an error

400 (Bad Request

Is there a place to set the file upload capacity other than the place I set?
It's confusing because there are too many size settings in various places.

I want to solve it first,
If possible, I would like to know how to solve it without using web.config.

Best regards

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
kisetu
  • 157
  • 12
  • 1
    I am not sure the web.config means anything in asp.net core.... also can you show the complete signature of the action? Can you provide a minimal reproducible example? – Jonathan Alfaro Jan 08 '21 at 06:35
  • Thanks for your comment. I wrote all the actions. The uploaded file is returned as it is. For web.config, I also don't think .net core is needed. But with this addition, at least 413 errors are gone. – kisetu Jan 08 '21 at 06:43
  • @kisetu, 400 indicate that the error request. Where do you get the file, can you share the form key-value, or share the client code? – Karney. Jan 08 '21 at 07:11
  • @karney Thanks for your comment. If the file size is small, the process will end normally without any problems, so I think it is a server-side problem. Since the client is React, there are many sources, so I thought it would be a hindrance to post it when asking a question, so I have not posted it. The file is now returned assuming a PowerPoint file, but it will be the same for other file formats. The contents of the file are all right. As long as it exceeds the size. – kisetu Jan 08 '21 at 07:49
  • I also posted a part of the client side source of the POST part – kisetu Jan 08 '21 at 08:07
  • Don't try to disable size restrictions. They're there for a reason. Without them, a hacker can freeze your site by sending an infinite stream of data. Doing so is trivial, just write the same byte to the request stream in an infinite loop. Increase the limit, don't try to disable it. – Panagiotis Kanavos Jan 08 '21 at 08:13
  • Thanks for your comment. Thank you for the reference article, I will confirm. I don't intend to leave it disabled either, but since I don't know the cause and I don't know what the restrictions are, I once disabled it. – kisetu Jan 08 '21 at 08:32
  • @Panagiotis Kanavos Thank you for the reference URL. When I looked at it, it said what I wanted to know. Many thanks to you too! – kisetu Jan 08 '21 at 08:43

1 Answers1

4

There is a limit on the size of files that the multipart form body allows for upload.

In UploadController.cs you need to change that limit as well in order to make it work:

Something like:

[HttpPost]
[RequestFormLimits(MultipartBodyLengthLimit = 1073741824)]
gijswijs
  • 1,958
  • 19
  • 24
  • Thank you for your reply! There is a setting called MultipartBodyLengthLimit. I didn't know this, but when I implemented it it worked fine! I am very grateful to you! However, even if I add this setting, if I delete web.config, I get a 413 error with another limitation. Is there a way to specify maxAllowedContentLength for Controller? As long as I use IIS, can I only specify it in web.config? Best Regard. – kisetu Jan 08 '21 at 08:37
  • As far as I can see the reference URL in the comment from @Panagiotis Kanavos, it seems that web.config is required for IIS. – kisetu Jan 08 '21 at 08:42
  • @kisetu only if you use IIS for deployment. Even then, you still need to configure your web app to allow large requests. And yes, you can configure limits per controller and action – Panagiotis Kanavos Jan 08 '21 at 08:49
  • Really big thanks for this bro. I'm trying to find this since 5 days... – Enes Kartal May 15 '22 at 09:05