在Asp.Net Core v3.1中增加上传文件的大小限制

16

我正在尝试在我的.NET Core v3.1 Blazor应用程序中上传多个文件,但我无法通过30MB的限制。
搜索后,我找到了Increase upload file size in Asp.Net core,并尝试了其中的建议,但并没有奏效。
所有找到的解决方案都涉及更改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;
            });
        });

上传控制器UploadController.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();
});

我有遗漏设置吗?难以置信这需要如此困难。

2个回答

2

使用[DisableRequestSizeLimit]属性修饰您的控制器方法。

[HttpPost]
[DisableRequestSizeLimit]
[Route("~/upload")]
public async Task<IActionResult> Upload(...)
{
    return Ok(...);
}

1
对我来说,这个是正确的答案。 - jazza1000

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>

似乎还有其他设置,比如限制每个操作方法的次数。您可能需要查看它们并选择最适合您需求的。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接