如何将大小超过 30000000 字节 (28.6MB) 的文件上传到 aws ec2 服务器(.net-core web api 项目)

How to upload files with size more than 30000000 Bytes (28.6MB) to aws ec2 server (.net-core web api project)

错误

当我从 swagger ui 测试超过 28.6MB(例如 30MB)的文件时,我收到以下错误响应:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>502 Bad Gateway</title>
</head><body>
<h1>Bad Gateway</h1>
<p>The proxy server received an invalid
response from an upstream server.<br />
</p>
<hr>
<address>Apache/2.4.29 (Ubuntu) Server at ec2-00-00-0-000.compute-1.amazonaws.com Port 80</address>
</body></html>

项目信息

到目前为止我做了什么

我添加了一个 web.config 文件,内容如下

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
  </system.webServer>

</configuration>

我将以下内容添加到 Startup.cs 文件

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<IISServerOptions>(options =>
    {
        options.MaxRequestBodySize = int.MaxValue;
    });

    services.Configure<FormOptions>(x =>
    {
        x.ValueLengthLimit = int.MaxValue;
        x.MultipartBodyLengthLimit = int.MaxValue;
        x.MultipartHeadersLengthLimit = int.MaxValue;
    });
    ...
    ...
    ...
}

测试模型class:

public class TestModel
{
    public IFormFile TestFile { get; set; }
}

测试控制器方法:

[Route("uploadtest")]
[HttpPost]
[Consumes("multipart/form-data")]
public async Task<ActionResult> UploadTest([FromForm] TestModel fff)
{
    return Ok();
}

额外信息

当我在本地电脑上从 visual studio (IIS Express) 运行 时,我没有收到错误响应。

您不会在 IIS Express 中收到错误,因为问题不在于项目,而在于运行它的托管服务器。在这种情况下使用 aws ec2。默认的最大文件上传是 2MB,所以超出这个范围的任何东西都不会通过。您将必须修改主机服务器中的配置。

这里有一个 link 希望能帮助解决问题:

我终于能够通过如下设置 KestrelServerOptions 来解决它:

services.Configure<KestrelServerOptions>(options =>
{
    options.Limits.MaxRequestBodySize  = int.MaxValue; 
});

由于 aws 使用的是 kestrel,所以问题只发生在 aws 中,而不是在我的本地 IISExpress 服务器中。

感谢:.