.NET Core 3.1升级至6.0后Max Request Body配置失效问题
解决.NET Core 3.1升级到6.0后大文件上传413错误的问题
针对升级项目中配置大文件上传限制无效的情况,可按以下步骤排查修复:
1. 统一Program.cs中的配置对象
你提供的代码中混用了builder.Services和services,升级项目若采用.NET 6的顶级语句模式,需统一使用builder.Services进行配置,避免因对象不一致导致配置不生效:
builder.Services.Configure<KestrelServerOptions>(options => { options.Limits.MaxRequestBodySize = int.MaxValue; }); builder.Services.Configure<IISServerOptions>(options => { options.MaxRequestBodySize = int.MaxValue; options.MaxRequestBodyBufferSize = int.MaxValue; }); builder.Services.Configure<FormOptions>(options => { options.ValueLengthLimit = int.MaxValue; options.MultipartBodyLengthLimit = int.MaxValue; options.MultipartHeadersLengthLimit = int.MaxValue; options.MultipartHeadersCountLimit = int.MaxValue; options.MultipartBoundaryLengthLimit = int.MaxValue; options.ValueCountLimit = int.MaxValue; });
若项目仍保留Startup.cs,则需在ConfigureServices方法内使用services对象完成上述配置,且确保配置代码位于AddControllers()/AddMvc()之前。
2. 更新web.config的IIS请求限制
升级后项目的web.config可能残留.NET Core 3.1的默认请求限制,需手动修改添加requestLimits配置:
<configuration> <system.webServer> <security> <requestFiltering> <!-- 设置为2GB,可根据需求调整 --> <requestLimits maxAllowedContentLength="2147483647" /> </requestFiltering> </security> </system.webServer> </configuration>
该配置用于覆盖IIS默认的30MB请求大小限制,是托管在IIS环境下必须设置的项。
3. 为上传接口添加特性标记
若仅针对特定接口允许大文件上传,可在对应控制器或Action上添加特性,确保局部配置覆盖全局:
// 针对整个控制器 [RequestSizeLimit(int.MaxValue)] public class UploadController : ControllerBase { // 或针对单个Action [HttpPost("upload")] [DisableRequestSizeLimit] public IActionResult UploadFile(IFormFile file) { // 上传逻辑 } }
4. 检查配置文件是否存在覆盖项
查看appsettings.json或appsettings.Development.json中是否存在Kestrel相关配置,若有则会覆盖代码中的设置,需移除或修改对应值:
// 若存在以下配置,需删除或调整MaxRequestBodySize "Kestrel": { "Limits": { "MaxRequestBodySize": 134217728 } }
5. 清理旧启动逻辑残留
若升级项目未完全移除Startup.cs的旧逻辑,需确保Configure方法中的中间件顺序正确:
UseRouting()需在UseAuthorization()之前MapControllers()需在所有中间件配置完成后调用
避免因中间件顺序错误导致配置无法生效。
内容的提问来源于stack exchange,提问作者Adil Dhada
相关产品推荐
相关产品推荐

