简体   繁体   English

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

[英]Increase upload file size in Asp.Net core

Currently, I am working with Asp.Net Core and MVC6 need to upload file size unlimited.目前,我正在使用 Asp.Net Core,MVC6 需要上传文件大小不受限制。 I have searched its solution but still not getting the actual answer.我已经搜索了它的解决方案,但仍然没有得到实际答案。

I have tried this link 我试过这个链接

If anyone have any idea please help.如果有人有任何想法请帮助。

Thanks.谢谢。

The other answers solve the IIS restriction .其他答案解决了 IIS 限制 However, as of ASP.NET Core 2.0, Kestrel server also imposes its own default limits.但是,从ASP.NET Core 2.0 开始,Kestrel 服务器也施加了自己的默认限制。

Github of KestrelServerLimits.cs KestrelServerLimits.cs 的 Github

Announcement of request body size limit and solution (quoted below)请求体大小限制及解决方案的公告(引用如下)

MVC Instructions MVC 说明

If you want to change the max request body size limit for a specific MVC action or controller, you can use the RequestSizeLimit attribute.如果要更改特定 MVC 操作或控制器的最大请求正文大小限制,可以使用RequestSizeLimit属性。 The following would allow MyAction to accept request bodies up to 100,000,000 bytes.以下将允许MyAction接受最多 100,000,000 字节的请求正文。

[HttpPost]
[RequestSizeLimit(100_000_000)]
public IActionResult MyAction([FromBody] MyViewModel data)
{

[DisableRequestSizeLimit] can be used to make request size unlimited. [DisableRequestSizeLimit]可用于使请求大小不受限制。 This effectively restores pre-2.0.0 behavior for just the attributed action or controller.这有效地为属性操作或控制器恢复了 2.0.0 之前的行为。

Generic Middleware Instructions通用中间件指令

If the request is not being handled by an MVC action, the limit can still be modified on a per request basis using the IHttpMaxRequestBodySizeFeature .如果请求不是由 MVC 操作处理,则仍然可以使用IHttpMaxRequestBodySizeFeature对每个请求修改限制。 For example:例如:

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

MaxRequestBodySize is a nullable long. MaxRequestBodySize是一个可为空的 long。 Setting it to null disables the limit like MVC's [DisableRequestSizeLimit] .将其设置为 null 会禁用 MVC 的[DisableRequestSizeLimit]等限制。

You can only configure the limit on a request if the application hasn't started reading yet;如果应用程序尚未开始读取,您只能配置请求的限制; otherwise an exception is thrown.否则抛出异常。 There's an IsReadOnly property that tells you if the MaxRequestBodySize property is in read-only state, meaning it's too late to configure the limit.有一个IsReadOnly属性会告诉您MaxRequestBodySize属性是否处于只读状态,这意味着配置限制为时已晚。

Global Config Instructions全局配置说明

If you want to modify the max request body size globally, this can be done by modifying a MaxRequestBodySize property in the callback of either UseKestrel or UseHttpSys .如果要全局修改最大请求正文大小,可以通过修改UseKestrelUseHttpSys回调中的MaxRequestBodySize属性来完成。 MaxRequestBodySize is a nullable long in both cases. MaxRequestBodySize在这两种情况下都是可空的 long。 For example:例如:

.UseKestrel(options =>
{
    options.Limits.MaxRequestBodySize = null;

or或者

.UseHttpSys(options =>
{
    options.MaxRequestBodySize = 100_000_000;

You're probably getting a 404.13 HTTP status code when you upload any file over 30MB.当您上传超过 30MB 的任何文件时,您可能会收到 404.13 HTTP 状态代码。 If you're running your ASP.Net Core application in IIS, then the IIS pipeline is intercepting your request before it hits your application.如果您在 IIS 中运行 ASP.Net Core 应用程序,则 IIS 管道会在请求到达您的应用程序之前拦截您的请求。

Update your web.config:更新您的 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>

Previous ASP.Net applications also needed this section, but it's not needed anymore in Core as your requests are handled by middleware:以前的 ASP.Net 应用程序也需要此部分,但在 Core 中不再需要它,因为您的请求由中间件处理:

  <system.web>
    <!-- Measured in kilobytes -->
    <httpRuntime maxRequestLength="1048576" />
  </system.web>

In ASP.NET Core 1.1 project that created by Visual Studio 2017, if you want to increase upload file size.在 Visual Studio 2017 创建的 ASP.NET Core 1.1 项目中,如果您想增加上传文件的大小。 You need to create web.config file by yourself, and add these content:您需要自己创建 web.config 文件,并添加以下内容:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <security>
      <requestFiltering>
        <!-- 1 GB -->
        <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
    </security>
  </system.webServer>
</configuration>

In Startup.cs file, add these content:在 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();
}

Maybe I am late here but here is the complete solution for uploading a file with a size of more than 30.0 MB in ASP.NET Core Version >=2.0:也许我来晚了,但这里是在 ASP.NET Core 版本 >=2.0 中上传大小超过 30.0 MB 的文件的完整解决方案:

You need to do the following three steps:您需要执行以下三个步骤:

1. IIS content length limit 1. IIS内容长度限制

The default request limit ( maxAllowedContentLength ) is 30,000,000 bytes, which is approximately 28.6 MB .默认请求限制 ( maxAllowedContentLength ) 为30,000,000字节,大约为28.6 MB Customize the limit in the web.config file:web.config文件中自定义限制:

<system.webServer>
    <security>
        <requestFiltering>
            <!-- Handle requests up to 1 GB -->
            <requestLimits maxAllowedContentLength="1073741824" />
        </requestFiltering>
    </security>
</system.webServer>

Note : without this application running on IIS would not work.注意:没有这个应用程序在 IIS 上运行将无法工作。

2. ASP.NET Core Request length limit 2. ASP.NET Core 请求长度限制

For application running on IIS:对于在 IIS 上运行的应用程序:

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

For application running on Kestrel:对于在 Kestrel 上运行的应用程序:

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

3. Form's MultipartBodyLengthLimit 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;
});

Adding all the above options will solve the problem related to the file upload with a size of more than 30.0 MB.添加以上所有选项将解决上传大于30.0 MB文件的相关问题。

In your startup.cs configure FormsOptions Http Feature:在您的startup.cs配置FormsOptions Http 功能:

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

Use IHttpMaxRequestBodySizeFeature Http Feature to configure MaxRequestBodySize使用IHttpMaxRequestBodySizeFeature Http 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();
    });
}

Kestrel :红隼

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

IIS --> web.config : 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>

Http.sys : Http.sys :

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


If you want to upload a very large file, potentially several GB large and you want to buffer it into a MemoryStream on the server, you will get an error message Stream was too long , because the capacity of the MemoryStream is int.MaxValue . 如果您想上传一个非常大的文件,可能有几 GB 大,并且您想将其缓冲到服务器上的MemoryStream ,您将收到错误消息Stream was too long ,因为MemoryStream的容量是int.MaxValue

You would ahve to implement your own custom MemoryStream class.您必须实现自己的自定义MemoryStream类。 But anyway, buffering such large files makes no sense.但无论如何,缓冲这么大的文件是没有意义的。

Using a web.config might compromise the architecture of .NET core and you might face problem while deploying the solution on Linux or on Mac.使用 web.config 可能会损害 .NET Core 的架构,并且在 Linux 或 Mac 上部署解决方案时可能会遇到问题。

Better is to use the Startup.cs for configuring this setting: Ex:更好的是使用 Startup.cs 来配置此设置:例如:

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

Here is a correction:这是一个更正:

You need to add web.config as well because when the request hits the IIS then it will search for the web.config and will check the maxupload length: sample :您还需要添加 web.config ,因为当请求到达 IIS 时,它将搜索 web.config 并检查最大上传长度:示例:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <security>
     <requestFiltering>
    <!-- 1 GB -->
     <requestLimits maxAllowedContentLength="1073741824" />
  </requestFiltering>
</security>
  1. In your web.config:在您的 web.config 中:

     <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2147483648" /> </requestFiltering> </security> </system.webServer>
  2. Manually edit the ApplicationHost.config file:手动编辑 ApplicationHost.config 文件:

    1. Click Start.单击开始。 In the Start Search box, type Notepad.在开始搜索框中,键入记事本。 Right-click Notepad, and then click "Run as administrator".右键单击记事本,然后单击“以管理员身份运行”。
    2. On the File menu, click Open.在文件菜单上,单击打开。 In the File name box, type "%windir%\\system32\\inetsrv\\config\\applicationhost.config", and then click Open.在“文件名”框中,键入“%windir%\\system32\\inetsrv\\config\\applicationhost.config”,然后单击“打开”。
    3. In the ApplicationHost.config file, locate the <requestLimits> node.ApplicationHost.config文件中,找到<requestLimits>节点。
    4. Remove the maxAllowedContentLength property.删除maxAllowedContentLength属性。 Or, add a value that matches the size of the Content-Length header that the client sends as part of the request.或者,添加一个与客户端作为请求的一部分发送的 Content-Length 标头大小匹配的值。 By default, the value of the maxAllowedContentLength property is 30000000.默认情况下, maxAllowedContentLength属性的值为 30000000。

      在此处输入图片说明

    5. Save the ApplicationHost.config file.保存ApplicationHost.config文件。

I will add this for completeness for other unlucky lads like me that ended up here, Source我会为其他像我这样的不幸小伙子们添加这个完整的内容, 来源

In Startup.cs :Startup.cs

services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 60000000;
});

In my case, I needed to increase the file upload size limit, but for a single page only.就我而言,我需要增加文件上传大小限制,但仅限于单个页面。

The file upload size limit is a security feature, and switching it off or increasing it globally often isn't a good idea.文件上传大小限制是一项安全功能,关闭它或全局增加它通常不是一个好主意。 You wouldn't want some script kiddie DOSing your login page with extremely large file uploads.您不希望某些脚本小子通过上传超大文件来对您的登录页面进行 DOS 操作。 This file upload limit gives you some protection against that, so switching it off or increasing it globally isn't always a good idea.此文件上传限制为您提供了一些保护,因此将其关闭或全局增加它并不总是一个好主意。

So, to increase the limit for a single page instead of globally:因此,要增加单个页面而不是全局的限制:

(I am using ASP.NET MVC Core 3.1 and IIS, Linux config would be different) (我使用的是 ASP.NET MVC Core 3.1 和 IIS,Linux 配置会有所不同)

1. Add a web.config 1.添加一个web.config

otherwise IIS (or IIS Express, if debugging in Visual Studio) will block the request with a "HTTP Error 413.1 - Request Entity Too Large" before it even reaches your code.否则 IIS(或 IIS Express,如果在 Visual Studio 中调试)将在它到达您的代码之前以“HTTP 错误 413.1 - 请求实体太大”阻止请求。

Note the "location" tag, which restricts the upload limit to a specific page请注意“位置”标签,它将上传限制限制为特定页面

You will also need the "handlers" tag, otherwise you will get a HTTP 404 error when browsing to that path您还需要“处理程序”标签,否则浏览到该路径时会出现 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>
  1. Next you will need to add the RequestSizeLimit attribute to your controller action, since Kestrel has its own limits too.接下来,您需要将RequestSizeLimit属性添加到您的控制器操作中,因为 Kestrel 也有自己的限制。 (you can instead do it via middleware as per other answers if you prefer) (如果您愿意,您可以根据其他答案通过中间件来代替)

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

and for completeness (if using MVC), your view and view model could look like this:为了完整性(如果使用 MVC),您的视图和视图模型可能如下所示:

view看法

<form method="post" enctype="multipart/form-data" asp-controller="SomeController" asp-action="Upload">
    <input type="file" name="@Model.File" />
</form>

View Model查看模型

public class SomeViewModel
{
    public IFormFile File { get; set; }
}

and, if you are uploading files greater than 128Mb via form post, you may run in to this error too并且,如果您通过表单发布上传大于 128Mb 的文件,您也可能会遇到此错误

InvalidDataException: Multipart body length limit 134217728 exceeded. InvalidDataException:超出多部分正文长度限制 134217728。

So on your controller action you could add the RequestFormLimits attribute因此,在您的控制器操作上,您可以添加RequestFormLimits属性

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

If you have scrolled down this far, that means you have tried above solutions.如果您已经向下滚动到这里,这意味着您已经尝试了上述解决方案。 If you are using latest NET CORE versions (5. . , 6. . ) and using IIS for hosting do this.如果您使用最新的 NET CORE 版本(5. . , 6. . )并使用 IIS 进行托管,请执行此操作。

  1. Add the web.config file to your project and then add the following code there:web.config文件添加到您的项目中,然后在其中添加以下代码:

     <?xml version="1.0" encoding="utf-8"?> <configuration> <system.webServer> <security> <requestFiltering> <.-- Handle requests up to 1 GB --> <requestLimits maxAllowedContentLength="1073741824" /> </requestFiltering> </security> </system.webServer> </configuration>
  2. Set up the Form Options and IIS Server Options in your Startup.cs file like this:Startup.cs文件中设置表单选项和 IIS 服务器选项,如下所示:

     services.Configure<IISServerOptions>(options => { options.MaxRequestBodySize = int.MaxValue; }); services.Configure<FormOptions>(o => { o.ValueLengthLimit = int.MaxValue; o.MultipartBodyLengthLimit = int.MaxValue; o.MultipartBoundaryLengthLimit = int.MaxValue; o.MultipartHeadersCountLimit = int.MaxValue; o.MultipartHeadersLengthLimit = int.MaxValue; o.BufferBodyLengthLimit = int.MaxValue; o.BufferBody = true; o.ValueCountLimit = int.MaxValue; });

I was trying to upload a big file but somehow the file wasn't reaching the controller action method and the parameters including the file one was still null like this:我试图上传一个大文件,但不知何故文件没有到达 controller 操作方法,包括文件一在内的参数仍然是null ,如下所示:

[HttpPost]
public async Task<IActionResult> ImportMedicalFFSFile(
    Guid operationProgressID,
    IFormFile file, // <= getting null here
    DateTime lastModifiedDate)
{
    ...
}

What fixed it was adding the [DisableRequestSizeLimit] attribute to the action method or the entire controller\BaseController if you prefer:解决它的方法是将[DisableRequestSizeLimit]属性添加到操作方法或整个 controller\BaseController(如果您愿意):

[DisableRequestSizeLimit]
public class ImportedFileController : BaseController
{
    ...
}

More info here:更多信息在这里:

DisableRequestSizeLimitAttribute Class DisableRequestSizeLimitAttribute Class

Using Visual Studio 2022 (v 17.1.6) and .net core 6, I did not need to change anything in the Program.cs class.使用 Visual Studio 2022 (v 17.1.6) 和 .net 核心 6,我不需要更改 Program.cs class 中的任何内容。 I only needed to add these two attributes (in addition to [HttpPost] and [Route]) to my controller method while running locally to accept a 100MB upload:我只需要在本地运行时将这两个属性(除了 [HttpPost] 和 [Route])添加到我的 controller 方法以接受 100MB 上传:

[RequestSizeLimit(100 * 1024 * 1024)]
[RequestFormLimits(MultipartBodyLengthLimit = 100 * 1024 * 1024)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM