Asp.Net core v3.1 增加上传文件大小

Pau*_*ems 9 c# file-upload iis-express kestrel-http-server asp.net-core-3.1

我正在尝试在我的 .NET Core v3.1 Blazor 应用程序中上传多个文件,但无法超过 30MB 的限制。
搜索这个我发现在 Asp.Net 核心中增加上传文件大小并尝试了建议,但它不起作用。
所有找到的解决方案都涉及更改 web.config,但我没有那个文件。
此外,我的应用程序在开发期间在 Visual Studio 2019 中运行,但也将作为 WebApp 在 Azure 上运行。

这些是我的设置:
program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>().ConfigureKestrel((context, options) =>
            {
                options.Limits.MaxRequestBodySize = null;
            });
        });
Run Code Online (Sandbox Code Playgroud)

上传控制器.cs

[Authorize]
[DisableRequestSizeLimit]
public class UploadController : BaseApiController
Run Code Online (Sandbox Code Playgroud)

Startup.cs 中的配置服务

services.AddSignalR(e => e.MaximumReceiveMessageSize = 102400000)
    .AddAzureSignalR(Configuration["Azure:SignalR:ConnectionString"]);

services.Configure<FormOptions>(options =>
{
    options.ValueLengthLimit = int.MaxValue;
    options.MultipartBodyLengthLimit = long.MaxValue; // <-- !!! long.MaxValue
    options.MultipartBoundaryLengthLimit = int.MaxValue;
    options.MultipartHeadersCountLimit = int.MaxValue;
    options.MultipartHeadersLengthLimit = int.MaxValue;
});
services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = int.MaxValue;
});
Run Code Online (Sandbox Code Playgroud)

在 Startup.cs 中配置

app.Use(async (context, next) =>
{
    context.Features.Get<IHttpMaxRequestBodySizeFeature>()
        .MaxRequestBodySize = null;

    await next.Invoke();
});
Run Code Online (Sandbox Code Playgroud)

我错过了一个设置吗?不敢相信这需要这么难。

bur*_*kay 1

在https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1找到了解决方案。最小化的解决方案只是新增一个web.config文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="52428800" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

似乎还有一些其他设置,例如限制每个操作方法。您可能需要仔细检查它们并选择最适合您需求的内容。

ps 今天早些时候在其他地方看到了相同的 web.config 解决方案。尝试将 30M 作为 maxAllowedContentLength,但它不适用于 ~10MB 的文本文件。现在意识到请求大小增加了两倍,因为文件内容作为二进制数组的字符串表示形式发送(这是一个问题,应该处理)。检查“网络”选项卡以了解确切的请求大小,并确保其不超过上述 web.config 设置。