首页 > 解决方案 > 在 Asp.Net core v3.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;
            });
        });

上传控制器.cs

[Authorize]
[DisableRequestSizeLimit]
public class UploadController : BaseApiController

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;
});

在 Startup.cs 中配置

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

    await next.Invoke();
});

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

标签: c#file-uploadiis-expressasp.net-core-3.1kestrel-http-server

解决方案


在https://docs.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>

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

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


推荐阅读