You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Asp.net Core 2.0 RequestSizeLimit特性不生效,文件超30MB返回404

Fixing 30MB Upload Limit & 404 Error in ASP.NET Core 2.0

Hey there! Let's dig into this file upload issue you're hitting. That 404 error when uploading files over 30MB is tricky because it often hides the real problem—usually a combination of server-side limits that aren't fully configured. Here's how to tackle each possible culprit step by step:

1. Configure ASP.NET Core's Form Request Limits

First, make sure your app is set to accept larger multipart form requests (since file uploads use multipart/form-data).

  • In your Startup.cs ConfigureServices method, add this to adjust form options:
    services.Configure<FormOptions>(options =>
    {
        // Set to 100MB (adjust the value as needed)
        options.MultipartBodyLengthLimit = 104857600;
        options.ValueLengthLimit = 104857600;
    });
    
  • Apply a size limit directly to your upload action using attributes:
    [HttpPost("upload")]
    [RequestSizeLimit(104857600)] // Enforce 100MB limit
    // Or use [DisableRequestSizeLimit] for no upper bound (not recommended for production)
    public async Task<IActionResult> Upload(IFormFile file)
    {
        // Your upload logic here
    }
    

2. Adjust Kestrel Server Limits

ASP.NET Core 2.0 uses Kestrel as the default web server, and it has a default 30MB request body limit—this is almost certainly why you're hitting that exact threshold!

Update your Program.cs to increase this limit:

public static IWebHost BuildWebHost(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .UseKestrel(options =>
        {
            // Set max request body size to 100MB
            options.Limits.MaxRequestBodySize = 104857600;
        })
        .Build();

3. If Deployed to IIS: Adjust IIS-Specific Limits

If you're running your app on IIS, there are two more settings to tweak in your web.config:

a. Request Filtering Limit

Add this under <system.webServer> to allow larger content lengths:

<system.webServer>
  <security>
    <requestFiltering>
      <!-- 100MB in bytes -->
      <requestLimits maxAllowedContentLength="104857600" />
    </requestFiltering>
  </security>
</system.webServer>

b. ASP.NET Core Module Timeout

Large uploads can take longer—prevent timeouts by adding requestTimeout to the <aspNetCore> node:

<aspNetCore processPath="dotnet" arguments=".\YourApp.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" requestTimeout="00:02:00" />

4. Validate Your Ajax Upload Code

Double-check that your Ajax request isn't adding unintended limits, and is properly formatted for file uploads:

function uploadMedia(isPhoto) {
    var formData = new FormData();
    var fileInput = document.getElementById('yourFileInputId');
    if (fileInput.files.length > 0) {
        formData.append('file', fileInput.files[0]);
    }

    $.ajax({
        url: '/api/media/upload', // Match your controller route
        type: 'POST',
        data: formData,
        processData: false, // Critical: don't process the form data
        contentType: false, // Critical: let the browser set the correct content type
        timeout: 120000, // 2 minutes to match IIS request timeout
        success: function(response) {
            console.log('Upload successful:', response);
        },
        error: function(xhr, status, error) {
            console.error('Upload failed:', xhr.status, error);
            // Check xhr.responseText for detailed error messages
        }
    });
}

Make sure you're not setting any custom maxFileSize parameters in your JS that might block larger files before they reach the server.

5. Check Logs for the Real Error

That 404 might be a red herring—sometimes servers return 404 when they actually reject a request for being too large. Enable logging to see the true issue:

  • In Startup.cs, add logging to capture request errors:
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(LogLevel.Debug);
        loggerFactory.AddDebug();
    
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
    
        // Rest of your middleware configuration
    }
    
  • Check the logs for messages like Request body too large—this will confirm which limit is still blocking your uploads.

Final Tip

Restart your app and server after making these changes—config updates often require a restart to take effect.

内容的提问来源于stack exchange,提问作者Slade

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:02:15