如何提高客户端向MVC Controller提交数据的上限?
解决MVC Controller接收大量数据的上限问题
ASP.NET MVC(.NET Framework)配置
修改Web.config中的
httpRuntime节点,调整请求大小限制:<system.web> <!-- maxRequestLength单位为KB,10240=10Mb --> <httpRuntime targetFramework="4.8" maxRequestLength="10240" requestLengthDiskThreshold="10240" /> </system.web>maxRequestLength控制允许的最大请求大小,requestLengthDiskThreshold是请求超过该值时写入磁盘的阈值,两者建议设为相同值。同时调整IIS层面的
requestFiltering限制(Web.config的system.webServer节点下):<system.webServer> <security> <requestFiltering> <!-- maxAllowedContentLength单位为字节,10485760=10Mb --> <requestLimits maxAllowedContentLength="10485760" /> </requestFiltering> </security> </system.webServer>此配置是IIS的全局请求大小限制,必须与
httpRuntime配合调整,否则仍会触发报错。
ASP.NET Core MVC配置
全局配置
在Program.cs(.NET 6+)或Startup.cs中配置请求大小限制:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // 配置表单请求选项 builder.Services.Configure<Microsoft.AspNetCore.Http.Features.FormOptions>(options => { options.MultipartBodyLengthLimit = 10 * 1024 * 1024; // 10Mb options.ValueLengthLimit = 10 * 1024 * 1024; }); // 若使用Kestrel服务器,额外配置Kestrel的请求限制 builder.WebHost.ConfigureKestrel(options => { options.Limits.MaxRequestBodySize = 10 * 1024 * 1024; // 10Mb }); var app = builder.Build(); app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();
单个Action配置
如果仅需针对特定接口调整,可使用[RequestSizeLimit]特性:
[HttpPost] [RequestSizeLimit(10 * 1024 * 1024)] // 限制该接口接收10Mb以内的请求 public IActionResult SubmitBulkData(List<YourDataModel> data) { // 业务处理逻辑 return Ok(); }
额外建议
- 调整的阈值需留足余量,但不宜过大,避免服务器资源过载。
- 若数据量持续增长,建议考虑分批提交数据或采用流式处理(直接读取Request.Body而非绑定到大集合),降低内存占用。
- 测试时需验证所有层面的限制均已调整,包括应用程序配置、Web服务器(IIS/Kestrel)设置。
内容的提问来源于stack exchange,提问作者Veysel Turan
相关产品推荐
相关产品推荐

