使用 Azure 应用服务更改 ASP.NET Core 3.1 应用的文件上传限制

Change file upload limits for an ASP.NET Core 3.1 App using Azure App Service

我有一个使用 ASP.NET Core 3.1 构建的解决方案。构建管道以发布到 Azure 中的应用服务。

问题是,我们无法上传大于 28MB 的文件。我们收到 413 错误 - 文件太大。这似乎是 IIS 问题,但 Azure 应用服务不使用 IIS。

浏览器返回的具体错误是这样的:

Request URL: https:xxxxxxxx
Request Method: POST
Status Code: 413 Request Entity Too Large
Remote Address: xx.xx.x.x
Referrer Policy: strict-origin-when-cross-origin
Content-Length: 67
Content-Type: text/html
Date: Sat, 23 Apr 2022 16:15:06 GMT
Server: Microsoft-IIS/10.0
Set-Cookie: 
Set-Cookie: 
X-Powered-By: ASP.NET
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 31438702

我们解决问题的步骤包括将 web.config 文件添加到我们的 wwwroot 目录,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="52428800" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

然后我们将以下代码添加到 ConfigureServices 中的启动文件中:

   services.Configure<IISServerOptions>(options =>
            {
                options.MaxRequestBodySize = 104857600;
            });

            services.Configure<FormOptions>(options =>
            {
                // Set the limit to 100 MB
                options.MultipartBodyLengthLimit = 104857600;
                options.ValueLengthLimit = 104857600;
                options.MultipartHeadersLengthLimit = 104857600;
            });

这些都没有改变结果。我们还找到了一个网站,该网站建议将以下代码添加到 Startup.但是这段代码打破了其他套路,所以我们把它拿出来。

   //app.Use(async (context, next) =>
            //{
            //    context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = 104857600;
            //    await next.Invoke();
            //});

我们的最后一步是请求 Microsoft 的支持。他们的回复确认 Azure App Services 不使用 IIS,并且此代码应该有效。他们还审查了我们的 Azure 配置,并报告说那里不需要进行任何更改。

那么,我做错了什么、遗漏了什么或遗漏了什么?

这是我们在 NET6 中的设置方式,在 3.1 中应该非常相似:

progam.cs

builder.WebHost.ConfigureKestrel(options =>
{
   options.Limits.MaxRequestBodySize = 256_000_000;
})
.UseIISIntegration()

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="256000000" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

很高兴@jimd12,经过我们的讨论,我们了解到您的问题已得到解决。

You found the discrepancy in the placement of the web.config file and placed it in the wwwroot directory, which you misplaced in the Project directory, and then the required file size upload worked.

作为答案发布,这样会对遇到类似问题的人有所帮助。即使您允许内容长度达到 high 值,请检查 web.config 文件的位置并参考此 SO thread,其中包含一些解决 Azure 应用服务文件上传限制问题的解决方法。