增加Asp.Net核心中的上传文件大小

Its*_*ere 46 asp.net-core-mvc asp.net-core

目前,我正在使用Asp.Net Core和MVC6需要上传文件大小无限制.我搜索了它的解决方案,但仍未得到实际的答案.

我试过这个链接

如果有人有任何想法请帮助.

谢谢.

Mat*_*kan 57

其他答案解决了IIS的限制.但是,从ASP.NET Core 2.0开始,Kestrel服务器也会施加自己的默认限制.

KestrelServerLimits.cs的Github

公告要求的车身尺寸限制和解决方案(引用如下)

MVC指令

如果要更改特定MVC操作或控制器的最大请求体大小限制,可以使用该RequestSizeLimit属性.以下内容允许MyAction接受最多100,000,000字节的请求主体.

[HttpPost]
[RequestSizeLimit(100_000_000)]
public IActionResult MyAction([FromBody] MyViewModel data)
{
Run Code Online (Sandbox Code Playgroud)

[DisableRequestSizeLimit]可用于使请求大小无限制.这有效地恢复了归因于动作或控制器的2.0.0之前的行为.

通用中间件说明

如果请求未由MVC操作处理,则仍可以使用每个请求修改限制IHttpMaxRequestBodySizeFeature.例如:

app.Run(async context =>
{
    context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = 100_000_000;
Run Code Online (Sandbox Code Playgroud)

MaxRequestBodySize是一个可以长篇大论.将其设置为null会禁用MVC之类的限制[DisableRequestSizeLimit].

如果应用程序尚未开始读取,您只能配置请求的限制; 否则抛出异常.有一个IsReadOnly属性可以告诉您MaxRequestBodySize属性是否处于只读状态,这意味着配置限制为时已晚.

全局配置说明

如果要全局修改最大请求主体大小,可以通过修改或者MaxRequestBodySize回调中的属性来完成.在两种情况下都是可以为空的.例如:UseKestrelUseHttpSysMaxRequestBodySize

.UseKestrel(options =>
{
    options.Limits.MaxRequestBodySize = null;
Run Code Online (Sandbox Code Playgroud)

要么

.UseHttpSys(options =>
{
    options.MaxRequestBodySize = 100_000_000;
Run Code Online (Sandbox Code Playgroud)

  • Mathew&@ Xav987你是否使用IFormFile进行模型绑定,或者对于大文件使用这里提到的长卷绕方式:https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view = aspnetcore-2.1 (4认同)
  • 就我而言,“ DisableRequestSizeLimit”属性还不够。我也不得不使用`RequestFormLimits`。像这样:`[HttpPost(“ upload”),DisableRequestSizeLimit,RequestFormLimits(MultipartBodyLengthLimit = Int32.MaxValue,ValueLengthLimit = Int32.MaxValue)]] (3认同)
  • @MarkRedman:我使用IFormFile。感谢您的链接。 (2认同)

Ash*_*Lee 36

当您上传任何超过30MB的文件时,您可能会获得404.13 HTTP状态代码.如果您在IIS中运行ASP.Net Core应用程序,则IIS管道会在您的请求到达您的应用程序之前拦截您的请求.

更新您的web.config:

<system.webServer>
    <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
    <!-- Add this section for file size... -->
    <security>
      <requestFiltering>
        <!-- Measured in Bytes -->
        <requestLimits maxAllowedContentLength="1073741824" />  <!-- 1 GB-->
      </requestFiltering>
    </security>
  </system.webServer>
Run Code Online (Sandbox Code Playgroud)

以前的ASP.Net应用程序也需要这一部分,但在Core中不再需要它,因为您的请求由中间件处理:

  <system.web>
    <!-- Measured in kilobytes -->
    <httpRuntime maxRequestLength="1048576" />
  </system.web>
Run Code Online (Sandbox Code Playgroud)

  • 如果您盲目地复制/粘贴上述内容,*&lt;cough&gt;* 就像我永远不会做的那样,*&lt;/cough&gt;*,请不要忘记这需要嵌套在 `&lt;configuration&gt;` 元素中。https://blogs.msdn.microsoft.com/azureossds/2016/06/15/uploading-large-files-to-azure-web-apps/ (7认同)

hai*_*ing 23

在Visual Studio 2017创建的ASP.NET Core 1.1项目中,如果要增加上载文件大小.您需要自己创建web.config文件,并添加以下内容:

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

在Startup.cs文件中,添加以下内容:

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

  services.AddMvc();
}
Run Code Online (Sandbox Code Playgroud)


Tan*_*jel 16

也许我来晚了,但这里是在 ASP.NET Core 版本 >=2.0 中上传大小超过 30.0 MB 的文件的完整解决方案:

您需要执行以下三个步骤:

1. IIS内容长度限制

默认请求限制 ( maxAllowedContentLength) 为30,000,000字节,大约为28.6 MB。自定义web.config文件中的限制:

<system.webServer>
    <security>
        <requestFiltering>
            <!-- Handle requests up to 1 GB -->
            <requestLimits maxAllowedContentLength="1073741824" />
        </requestFiltering>
    </security>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

注意:没有这个应用程序在 IIS 上运行将无法工作。

2. ASP.NET Core 请求长度限制

对于在 IIS 上运行的应用程序:

services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = int.MaxValue;
});
Run Code Online (Sandbox Code Playgroud)

对于在 Kestrel 上运行的应用程序:

services.Configure<KestrelServerOptions>(options =>
{
    options.Limits.MaxRequestBodySize = int.MaxValue; // if don't set default value is: 30 MB
});
Run Code Online (Sandbox Code Playgroud)

3. Form 的 MultipartBodyLengthLimit

services.Configure<FormOptions>(options =>
{
    options.ValueLengthLimit = int.MaxValue;
    options.MultipartBodyLengthLimit = int.MaxValue; // if don't set default value is: 128 MB
    options.MultipartHeadersLengthLimit = int.MaxValue;
});
Run Code Online (Sandbox Code Playgroud)

添加以上所有选项将解决上传大于30.0 MB文件的相关问题。


Leg*_*nds 15

在您startup.cs配置FormsOptionsHttp 功能中:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<FormOptions>(o =>  // currently all set to max, configure it to your needs!
    {
        o.ValueLengthLimit = int.MaxValue;
        o.MultipartBodyLengthLimit = long.MaxValue; // <-- !!! long.MaxValue
        o.MultipartBoundaryLengthLimit = int.MaxValue;
        o.MultipartHeadersCountLimit = int.MaxValue;
        o.MultipartHeadersLengthLimit = int.MaxValue;
    });
}
Run Code Online (Sandbox Code Playgroud)

使用IHttpMaxRequestBodySizeFeatureHttp Feature 进行配置MaxRequestBodySize

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.Use(async (context, next) =>
    {
        context.Features.Get<IHttpMaxRequestBodySizeFeature>().MaxRequestBodySize = null; // unlimited I guess
        await next.Invoke();
    });
}
Run Code Online (Sandbox Code Playgroud)

红隼

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

IIS --> web.config :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.web>
    <!-- ~ 2GB -->
    <httpRuntime maxRequestLength="2147483647" /> // kbytes
  </system.web>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- ~ 4GB -->
        <requestLimits maxAllowedContentLength="4294967295" /> // bytes
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)

Http.sys :

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


如果你想上传一个非常大的文件,可能有几 GB 大,并且你想将它缓冲到MemoryStream服务器上,你会收到一条错误消息Stream was too long,因为它的容量MemoryStreamint.MaxValue.

您必须实现自己的自定义MemoryStream类。但无论如何,缓冲这么大的文件是没有意义的。


Cod*_*key 12

就我而言,我需要增加文件上传大小限制,但仅限于单个页面。

文件上传大小限制是一项安全功能,全局关闭或增加它通常不是一个好主意。您不希望某些脚本小子通过上传非常大的文件来攻击您的登录页面。此文件上传限制为您提供了一些防范措施,因此将其关闭或全局增加它并不总是一个好主意。

因此,要增加单个页面而不是全局的限制:

(我使用的是 ASP.NET MVC Core 3.1 和 IIS,Linux 配置会有所不同)

1.添加web.config

否则,IIS(或 IIS Express,如果在 Visual Studio 中调试)将在请求到达您的代码之前阻止该请求,并显示“HTTP 错误 413.1 - 请求实体太大”。

注意“location”标签,它将上传限制限制到特定页面

您还需要“handlers”标签,否则浏览该路径时会收到 HTTP 404 错误

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="SomeController/Upload">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <security>
        <requestFiltering>
          <!--unit is bytes => 500 Mb-->
          <requestLimits maxAllowedContentLength="524288000" />
        </requestFiltering>
      </security>
    </system.webServer>
  </location>
</configuration>
Run Code Online (Sandbox Code Playgroud)
  1. 接下来,您需要将RequestSizeLimit属性添加到控制器操作中,因为 Kestrel 也有其自己的限制。(如果您愿意,您可以按照其他答案通过中间件来完成此操作)

     [HttpPost]
     [RequestSizeLimit(500 * 1024 * 1024)]       //unit is bytes => 500Mb
     public IActionResult Upload(SomeViewModel model)
     {
         //blah blah
     }
    
    Run Code Online (Sandbox Code Playgroud)

为了完整性(如果使用 MVC),您的视图和视图模型可能如下所示:

看法

<form method="post" enctype="multipart/form-data" asp-controller="SomeController" asp-action="Upload">
    <input type="file" name="@Model.File" />
</form>
Run Code Online (Sandbox Code Playgroud)

查看模型

public class SomeViewModel
{
    public IFormFile File { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

并且,如果您通过表单发布上传大于 128Mb 的文件,也可能会遇到此错误

InvalidDataException:超出了多部分正文长度限制 134217728。

因此,您可以在控制器操作上添加RequestFormLimits属性

 [HttpPost]
 [RequestSizeLimit(500 * 1024 * 1024)]       //unit is bytes => 500Mb
 [RequestFormLimits(MultipartBodyLengthLimit = 500 * 1024 * 1024)]
 public IActionResult Upload(SomeViewModel model)
 {
     //blah blah
 }
Run Code Online (Sandbox Code Playgroud)


小智 11

使用 Visual Studio 2022(v 17.1.6)和 .net core 6,我不需要更改 Program.cs 类中的任何内容。我只需要在本地运行时将这两个属性(除了 [HttpPost] 和 [Route] 之外)添加到我的控制器方法中即可接受 100MB 上传:

[RequestSizeLimit(100 * 1024 * 1024)]
[RequestFormLimits(MultipartBodyLengthLimit = 100 * 1024 * 1024)]
Run Code Online (Sandbox Code Playgroud)


Ksh*_*gra 6

使用 web.config 可能会损害 .NET Core 的架构,并且在 Linux 或 Mac 上部署解决方案时可能会遇到问题。

更好的是使用 Startup.cs 来配置此设置:例如:

services.Configure<FormOptions>(x =>
{
    x.ValueLengthLimit = int.MaxValue;
    x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
});
Run Code Online (Sandbox Code Playgroud)

这是一个更正:

您还需要添加 web.config ,因为当请求到达 IIS 时,它将搜索 web.config 并检查最大上传长度:示例:

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