111

Currently, I am working with Asp.Net Core and MVC6 need to upload file size unlimited. 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.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Itsathere
  • 1,210
  • 2
  • 9
  • 5

14 Answers14

101

The other answers solve the IIS restriction. However, as of ASP.NET Core 2.0, Kestrel server also imposes its own default limits.

Github of KestrelServerLimits.cs

Announcement of request body size limit and solution (quoted below)

MVC Instructions

If you want to change the max request body size limit for a specific MVC action or controller, you can use the RequestSizeLimit attribute. The following would allow MyAction to accept request bodies up to 100,000,000 bytes.

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

[DisableRequestSizeLimit] can be used to make request size unlimited. This effectively restores pre-2.0.0 behavior for just the attributed action or controller.

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. For example:

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

MaxRequestBodySize is a nullable long. Setting it to null disables the limit like MVC's [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.

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. MaxRequestBodySize is a nullable long in both cases. For example:

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

or

.UseHttpSys(options =>
{
    options.MaxRequestBodySize = 100_000_000;
Matthew Steven Monkan
  • 8,170
  • 4
  • 53
  • 71
  • What is the largest file you or anyone else been able to upload successfully with this ? I'm just curious as I'm working on a project that will require large uploads for secure communications. – Radar5000 Apr 05 '18 at 14:43
  • 1
    I've uploaded 10 GB files. I think you would only be limited by having a max server timeout setting be reached, or memory/file storage limit being reached depending on how you stream/store the files. – Matthew Steven Monkan Apr 06 '18 at 01:48
  • 5
    In my case, the `DisableRequestSizeLimit` attribute was not enought. I had to use the `RequestFormLimits` too. Like this : `[HttpPost("upload"), DisableRequestSizeLimit, RequestFormLimits(MultipartBodyLengthLimit = Int32.MaxValue, ValueLengthLimit = Int32.MaxValue)]` – Xav987 Oct 23 '18 at 13:57
  • 4
    Mathew & @Xav987 do you use model binding with IFormFile or the long winded way round mentioned here for large files: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.1 – Mark Redman Nov 01 '18 at 13:38
  • @Xav987: Thanks, I was looking at the long winded way but have avoided that with by setting both attributes. – Mark Redman Nov 05 '18 at 10:52
  • For ASP.NET Core Version >= 2.0 : [Uploading file with size more than 30.0 MB in ASP.NET Core Version >=2.0](https://stackoverflow.com/a/60964837/5928070) – TanvirArjel Apr 01 '20 at 07:27
51

You're probably getting a 404.13 HTTP status code when you upload any file over 30MB. If you're running your ASP.Net Core application in IIS, then the IIS pipeline is intercepting your request before it hits your application.

Update your 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:

  <system.web>
    <!-- Measured in kilobytes -->
    <httpRuntime maxRequestLength="1048576" />
  </system.web>
Ashley Lee
  • 3,810
  • 1
  • 18
  • 26
  • 1
    You probably meant 30MB, not GB – jao Sep 05 '17 at 14:57
  • 9
    If you're blindly copying/pasting the above, ** like I would never do, **, don't forget this needs to be nested in the `` element. https://blogs.msdn.microsoft.com/azureossds/2016/06/15/uploading-large-files-to-azure-web-apps/ – JackMorrissey Dec 13 '18 at 19:42
44

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:

You need to do the following three steps:

1. IIS content length limit

The default request limit (maxAllowedContentLength) is 30,000,000 bytes, which is approximately 28.6 MB. Customize the limit in the web.config file:

<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.

2. ASP.NET Core Request length limit

For application running on IIS:

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

For application running on Kestrel:

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

3. Form's 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.

TanvirArjel
  • 30,049
  • 14
  • 78
  • 114
  • i did all 3 steps mentioned above, still i am getting CORS issue, if you can add some debugging stuff then it will help someone. - i have just skipped this one services.Configure(options => as i am using web api 2.1 c# – Var Oct 19 '20 at 13:46
  • For Kestrel I had to set `services.Configure(options => options.Limits.MaxRequestBodySize = );` – Peheje Jan 25 '21 at 07:32
  • Does this also work for JSON POST body? – JustAMartin Aug 09 '22 at 13:13
32

In ASP.NET Core 1.1 project that created by Visual Studio 2017, if you want to increase upload file size. You need to create web.config file by yourself, and add these content:

<?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:

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

  services.AddMvc();
}
haiwuxing
  • 1,162
  • 10
  • 12
24

In your startup.cs configure FormsOptions Http Feature:

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

UseIHttpMaxRequestBodySizeFeature Http Feature to configure 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:

<?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:

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`.

You would ahve to implement your own custom MemoryStream class. But anyway, buffering such large files makes no sense.

jaredbaszler
  • 3,941
  • 2
  • 32
  • 40
Legends
  • 21,202
  • 16
  • 97
  • 123
10

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. 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)

1. Add a 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.

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

<?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. (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:

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

InvalidDataException: Multipart body length limit 134217728 exceeded.

So on your controller action you could add the RequestFormLimits attribute

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

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.

Better is to use the Startup.cs for configuring this setting: Ex:

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 :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <security>
     <requestFiltering>
    <!-- 1 GB -->
     <requestLimits maxAllowedContentLength="1073741824" />
  </requestFiltering>
</security>
Maximilian Ast
  • 3,369
  • 12
  • 36
  • 47
Kshitij Jhangra
  • 577
  • 7
  • 14
5

Using Visual Studio 2022 (v 17.1.6) and .net core 6, I did not need to change anything in the 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:

[RequestSizeLimit(100 * 1024 * 1024)]
[RequestFormLimits(MultipartBodyLengthLimit = 100 * 1024 * 1024)]
MPowerGuy
  • 61
  • 1
  • 4
  • When passed to the dockerized environment, it is giving bad request :S – Enrique Mingyar Torrez Hinojos Nov 25 '22 at 18:46
  • I'm sure you tried this but if you run the same code and configuration outside of docker does it allow the larger upload? I have very little docker exp but would imagine it doesn't get involved at the level needed to restrict a single inbound POST, yeah? – MPowerGuy Mar 20 '23 at 00:06
4
  1. In your web.config:

    <system.webServer>
      <security>
        <requestFiltering>
          <requestLimits maxAllowedContentLength="2147483648" />
        </requestFiltering>
      </security>
    </system.webServer>
    
  2. Manually edit the ApplicationHost.config file:

    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.
    3. In the ApplicationHost.config file, locate the <requestLimits> node.
    4. Remove the maxAllowedContentLength property. Or, add a value that matches the size of the Content-Length header that the client sends as part of the request. By default, the value of the maxAllowedContentLength property is 30000000.

      enter image description here

    5. Save the ApplicationHost.config file.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
Thomas Verhoeven
  • 238
  • 3
  • 16
4

I will add this for completeness for other unlucky lads like me that ended up here, Source

In Startup.cs:

services.Configure<FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 60000000;
});
eddyP23
  • 6,420
  • 7
  • 49
  • 87
2

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.

  1. Add the web.config file to your project and then add the following code there:

    <?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:

     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;
     });
    
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Khatai M
  • 51
  • 4
1

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:

[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]
public class ImportedFileController : BaseController
{
    ...
}

More info here:

DisableRequestSizeLimitAttribute Class

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
0
var myLargeString = "this is a large string that I want to send to the server";

$.ajax({
  type: "POST",
  url: "/MyController/MyAction",
  contentType: "application/json",
  data: JSON.stringify({ largeString: myLargeString }),
  processData: false,
  success: function (data) {
    console.log("Data received from the server: " + data);
  },
  error: function (xhr, status, error) {
  console.log("Error: " + error);
  }
});
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 20 '23 at 18:48
  • This doesn't answer the question. You're showing how to post a large string via HTML. This question is about increasing the server-side limit for uploading files on ASP.NET Core. – Jeremy Caney Apr 24 '23 at 20:45
0

The only fix that worked for me is to modify Program.cs of the relevant project as follows

var builder = WebApplication.CreateBuilder(args);

builder.WebHost.ConfigureKestrel(options =>
{
  long mb = 1048576;
  options.Limits.MaxRequestBodySize = 150 * mb;
});

var app = builder.Build();
app.Run();
trubby22
  • 21
  • 3
  • 1
    Thank you for your interest in contributing to the Stack Overflow community. This question already has quite a few answers—including one that has been extensively validated by the community. Are you certain your approach hasn’t been given previously? **If so, it would be useful to explain how your approach is different, under what circumstances your approach might be preferred, and/or why you think the previous answers aren’t sufficient.** Can you kindly [edit] your answer to offer an explanation? – Jeremy Caney May 18 '23 at 17:48