.Net Core 中接收上传文件时会遇到这个异常: Multipart body length limit 16384 exceeded
两种解决办法
1.修改配置
在startup的ConfigureServices方法中添加以下代码
services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;
x.ValueCountLimit = int.MaxValue;
x.MultipartBodyLengthLimit = long.MaxValue;
x.MultipartBoundaryLengthLimit = int.MaxValue;
x.BufferBodyLengthLimit = long.MaxValue;
x.BufferBody = true;
x.MemoryBufferThreshold = int.MaxValue;
x.KeyLengthLimit = int.MaxValue;
x.MultipartHeadersLengthLimit = int.MaxValue;
x.MultipartHeadersCountLimit = int.MaxValue;
});
在Program类的CreateHostBuilder方法中添加
.UseKestrel(options=> {
options.Limits.MaxRequestBodySize = null;
});
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>()
.UseUrls("http://*:365")
.UseKestrel(options=> {
options.Limits.MaxRequestBodySize = null;
});
});
在控制器上标识
[DisableRequestSizeLimit]
[HttpPost]
[DisableRequestSizeLimit]
public async Task<dynamic> UploadFileAsync(){
if (Request.Form.Files.Count == 0) return BadRequest("Upload Failed: no file.");
var file = Request.Form.Files[0];
if (file.Length < 1) return BadRequest("Upload Failed: file is empty.");
}
2.使用[FromForm]IFormCollection formData 接收
接口函数中不直接使用 Request.Form, 而需要将Form放到参数中。即:
public async Task<dynamic> UploadFileAsync([FromForm]IFormCollection formData){
// 这边直接使用formData
}