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

ASP.NET Core API大文件上传遇请求体过大报错,如何解决?

解决ASP.NET Core API大文件上传(Nginx反向代理+Kestrel)的请求体过大问题

你遇到的报错里的30000000字节(约28.6MB)限制,需要从Kestrel配置、ASP.NET Core全局请求限制、Nginx反向代理配置三个层面解决,以下是具体步骤:

1. 修正认知:dotnet Api.dll默认使用Kestrel

你通过dotnet Api.dll运行API时,默认就是以Kestrel作为底层Web服务器,哪怕前端有Nginx反向代理,Kestrel的请求大小限制依然会生效,这是你之前忽略的关键点。

2. 配置Kestrel的最大请求体大小

方式1:通过代码配置(适配所有.NET Core版本)

  • 如果是.NET 6+的Program.cs:
var builder = WebApplication.CreateBuilder(args);

// 配置Kestrel最大请求体大小,设为null表示无限制,也可设具体数值(比如10*1024*1024*1024表示10GB)
builder.WebHost.ConfigureKestrel(serverOptions =>
{
    serverOptions.Limits.MaxRequestBodySize = null;
});

// 其他服务配置...
var app = builder.Build();

// 中间件配置...
app.Run();
  • 如果是.NET 5及之前的Startup.cs:
public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
            // 配置Kestrel最大请求体大小
            webBuilder.ConfigureKestrel(serverOptions =>
            {
                serverOptions.Limits.MaxRequestBodySize = null;
            });
        });

3. 全局配置ASP.NET Core的请求体及表单限制

除了你已配置的FormOptions,还需要全局取消请求体大小限制:

  • 在.NET 5及之前的Startup.cs的Configure方法中添加中间件:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 其他中间件(如app.UseRouting()等)...

    // 全局设置请求体无限制
    app.Use(async (context, next) =>
    {
        var feature = context.Features.Get<IHttpMaxRequestBodySizeFeature>();
        if (feature != null)
        {
            feature.MaxRequestBodySize = null;
        }
        await next();
    });

    // 其他中间件...
}
  • 如果是.NET 6+的Program.cs,直接在中间件链中添加:
var app = builder.Build();

// 全局设置请求体无限制
app.Use(async (context, next) =>
{
    var feature = context.Features.Get<IHttpMaxRequestBodySizeFeature>();
    if (feature != null)
    {
        feature.MaxRequestBodySize = null;
    }
    await next();
});

// 其他中间件配置...
app.Run();

同时优化你已有的FormOptions配置(避免int溢出问题):

// .NET 6+用builder.Services,.NET 5及之前用services
services.Configure<FormOptions>(x =>
{
    x.ValueLengthLimit = int.MaxValue;
    x.MultipartBodyLengthLimit = long.MaxValue; // 改用long类型避免大文件溢出
    x.MultipartHeadersLengthLimit = int.MaxValue;
});

4. 修改Nginx的请求大小限制

报错中的30MB左右限制大概率来自Nginx的默认配置,需要修改Nginx配置文件(如nginx.conf或站点独立配置文件):
在http块、server块或对应API的location块中添加:

# 设置允许的最大请求体大小,这里设为10GB,可根据实际需求调整
client_max_body_size 10G;

修改完成后重启Nginx服务:

# Linux系统重启命令
sudo systemctl restart nginx

# Windows系统(取决于安装方式)
nginx -s reload

验证配置

完成以上三步后,重新启动API和Nginx,测试大文件上传即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 14:40:18