如何实现ASP.NET Core控制器上传文件大小限制可配置化
从配置文件设置.NET 6/.NET 8文件上传大小限制
问题背景
我有一个处理大文件上传的FileController,为支持超过30MB的文件,原本使用RequestSizeLimit特性硬编码设置150MB的限制,代码如下:
private const long _maxFileSize = 1000 * 1000 * 150; // 150 Mb [HttpPost] [RequestSizeLimit(_maxFileSize)] public async Task<ActionResult<IList<UploadResult>>> PostFile([FromForm] IEnumerable<IFormFile> files) { // .... }
这段代码可正常运行,但我希望将硬编码的文件限制值存入配置文件——而RequestSizeLimit特性无法直接读取配置。
尝试通过修改Program.cs的中间件管道读取配置并设置限制,参考代码如下:
app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), appBuilder =>{ context.Features.Get<IHttpMaxRequestBodySizeFeature>() .MaxRequestBodySize = 1000 * 1000 * 150; // 150 Mb; //TODO: read hardcoded limit from configuration });
但这段代码无法编译,报错:
CS0103 - 名称“context”在当前上下文中不存在
当前使用.NET 6,准备切换到.NET 8,请问如何修改上述代码使其可用?或有没有其他从配置设置RequestSizeLimit的方法?
解决方案
正确的做法是在UseWhen内部添加自定义中间件,在中间件委托中获取请求上下文,再读取配置并设置大小限制。最终代码如下:
var app = builder.Build(); const long _defaultMaxRequestBodySize = 1024 * 1024 * 75; app.UseWhen(context => context.Request.Path.StartsWithSegments("/api/File"), appBuilder => { appBuilder.Use(async (context, next) => { var maxRequestBodySizeFeature = context.Features.Get<IHttpMaxRequestBodySizeFeature>() ?? throw new ArgumentNullException("IHttpMaxRequestBodySizeFeature"); maxRequestBodySizeFeature.MaxRequestBodySize = builder.Configuration.GetValue<long>("MaxRequestBodySize", _defaultMaxRequestBodySize); await next.Invoke(); }); });
代码说明
- 使用
UseWhen匹配指定API路径(/api/File),仅对该路径下的请求应用大小限制 - 在自定义中间件中获取
IHttpMaxRequestBodySizeFeature,该特性用于控制请求体的最大大小 - 通过
builder.Configuration读取配置文件中的MaxRequestBodySize值,同时设置75MB作为默认 fallback 值 - 调用
next.Invoke()继续执行后续中间件管道
内容的提问来源于stack exchange,提问作者Peter
相关产品推荐
相关产品推荐

