环境相关:
- asp.net core 3.1
- IIS
- html
问题:
需要通过file upload控件上传大小超过30M的文件到服务器, 因为30M是IIS的默认POST Body大小限制,所以需要手动修改这个限制。
解决方案:
- 在Asp.net core中的
Program.cs
里,将CreateWebHostBuilder
方法修改如下修改Kestrel服务器的限制
public static IWebHostBuilder CreateWebHostBuilder(string[] args) { return WebHost.CreateDefaultBuilder(args) .ConfigureKestrel((context, options) => { options.Limits.MaxRequestBodySize = 1048576000; }) .UseStartup<Startup>(); }
- 在Asp.net core中的
Startup.cs
里,在ConfigureServices
方法中加入如下方法,修改多文件上传时的大小限制
services.AddMvc(); services.Configure<FormOptions>(x => { x.ValueLengthLimit = int.MaxValue; x.MultipartBodyLengthLimit = int.MaxValue; });
- 在对应的Controller文件(我这里是
FilesControleler.cs
文件)Post方法头部添加如下说明[DisableRequestSizeLimit],取消对应方法的大小限制
// POST: api/Files [HttpPost] [DisableRequestSizeLimit] //就是这句话! public IActionResult UploadFile([FromForm(Name = "files")] List<IFormFile> files) { try { SaveFile(files, Alias); return Ok(new { files.Count, Size = SizeConverter(files.Sum(f => f.Length)) }); } catch (Exception exception) { return BadRequest($"Error: {exception.Message}"); } }
- 在项目根目录添加
web.config
文件,asp.net core默认是没有这个文件的,自己添加,用来修改IIS服务器对文件大小的限制
<?xml version="1.0" encoding="utf-8"?><configuration> <!-- To customize the asp.net core module uncomment and edit the following section. For more info see https://go.microsoft.com/fwlink/?linkid=838655 --> <system.webServer> <handlers> <remove name="aspNetCore" /> <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" /> </handlers> <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="InProcess"> <environmentVariables> <environmentVariable name="COMPLUS_ForceENC" value="1" /> <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development" /> </environmentVariables> </aspNetCore> <security> <requestFiltering> <!-- This will handle requests up to 1GB --> <!--主要就是下面这句,重新设定服务器允许的单次请求大小--> <requestLimits maxAllowedContentLength="1048576000" /> </requestFiltering> </security> </system.webServer></configuration>
OK,这样file upload文件上传大小就被限制在了1G。
文章转载于:https://www.jianshu.com/p/578a31a29666
还没有人抢沙发呢~