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

VS22中.NET Core 7开发模式下HTTP 413请求过大问题求助

.NET Core 7 上传50MB文件报413错误的有效解决方案

1. 修正appsettings.json配置(原配置存在无效项)

原配置里的HttpRuntime是ASP.NET Framework专属配置,.NET Core环境下不生效,且maxAllowedContentLength的放置位置错误。正确配置如下:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "IISServer": {
    "MaxRequestBodySize": 524288000
  },
  "Kestrel": {
    "Limits": {
      "MaxRequestBodySize": 524288000
    }
  }
}
  • Kestrel.Limits.MaxRequestBodySize:设置Kestrel服务器的最大请求体大小,524288000对应500MB,完全覆盖50MB上传需求
  • IISServer.MaxRequestBodySize:如果使用IIS Express调试,必须配置该项

2. 简化并修正Program.cs中的配置

原配置存在重复配置Kestrel的冲突问题,统一调整为:

var builder = WebApplication.CreateBuilder(args);

// 配置Kestrel最大请求体大小
builder.WebHost.ConfigureKestrel(options =>
{
    options.Limits.MaxRequestBodySize = 524288000; // 500MB
});

// 配置IIS服务器(IIS Express调试时生效)
builder.Services.Configure<IISServerOptions>(options =>
{
    options.MaxRequestBodySize = 524288000; // 500MB
});

// 配置表单上传限制
builder.Services.Configure<Microsoft.AspNetCore.Http.Features.FormOptions>(options =>
{
    options.MultipartBodyLengthLimit = 524288000; // 500MB,预留冗余空间避免刚好卡阈值
    options.ValueLengthLimit = int.MaxValue;
    options.MultipartHeadersLengthLimit = int.MaxValue;
});

// 其他服务配置...

var app = builder.Build();

// 中间件配置...

app.Run();
  • 移除重复的KestrelServerOptions配置,统一通过builder.WebHost.ConfigureKestrel配置
  • 补充ValueLengthLimit和MultipartHeadersLengthLimit,避免表单其他维度的大小限制触发错误

3. 控制器/动作添加特性(关键生效步骤)

针对处理文件上传的接口,必须添加[RequestSizeLimit]和[RequestFormLimits]特性,确保局部配置覆盖全局:

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/[controller]")]
public class UploadController : ControllerBase
{
    [HttpPost("file")]
    [RequestSizeLimit(524288000)]
    [RequestFormLimits(MultipartBodyLengthLimit = 524288000)]
    public async Task<IActionResult> UploadFile(IFormFile file)
    {
        // 文件处理逻辑...
        return Ok();
    }
}
  • 全局配置可能因局部特性缺失而不生效,这一步是很多配置失效的核心原因

4. 检查IIS Express的applicationhost.config(使用IIS Express时)

打开项目根目录下.vs\你的项目名\config\applicationhost.config文件,找到对应站点节点,添加如下配置:

<location path="你的站点名称">
    <system.webServer>
        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="524288000" />
            </requestFiltering>
        </security>
    </system.webServer>
</location>
  • 修改后重启Visual Studio和IIS Express,确保配置加载

验证流程

  1. 清理项目并重新生成
  2. 重启Visual Studio,确保所有配置生效
  3. 测试上传50MB文件,确认413错误消失

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 05:58:31