本文基于.NET Core 3.1开发。
1、设置文件上传大小
打开Program.cs文件,添加如下代码:
webBuilder.UseStartup<Startup>().
ConfigureKestrel(options =>
{
//设置文件上传大小为int的最大值
options.Limits.MaxRequestBodySize = int.MaxValue;
});
打开Startup.cs,再ConfigureServices添加如下代码:
//通过设置即重置文件上传的大小限制
services.Configure<FormOptions>(o =>
{
o.BufferBodyLengthLimit = long.MaxValue;
o.MemoryBufferThreshold = int.MaxValue;
o.ValueLengthLimit = int.MaxValue;
o.MultipartBodyLengthLimit = long.MaxValue;
o.MultipartBoundaryLengthLimit = int.MaxValue;
o.MultipartHeadersCountLimit = int.MaxValue;
o.MultipartHeadersLengthLimit = int.MaxValue;
});
2、文件上传
编写一个文件包含参数的API,进行文件上传,使用【 [DisableRequestSizeLimit]】特性,解除上传大小限值:
/// <summary>
/// 事件上传
/// </summary>
/// <param name="file">文件信息</param>
/// <param name="Id">Id</param>
/// <returns></returns>
[HttpPost]
[DisableRequestSizeLimit]
public async Task<IActionResult> EventUpload(IFormFile file, int Id)
{
if (file == null)
{
return Ok(new { code="201",msg= "请上传文件" });
}
var fileExtension = Path.GetExtension(file.FileName);
if (fileExtension == null)
{
return Ok(new { code = "201", msg = "文件无后缀信息" });
}
long length = file.Length;
if (length > 1024 * 1024 * 300) //200M
{
return Ok(new { code = "201", msg = "上传文件不能超过300M" });
}
string Paths = Path.GetFullPath("..");
string guid = Guid.NewGuid().ToString();
string stringPath = Paths + $"BufFile\\OutFiles\\DownLoadFiles\\Video\\{guid}\\";
string filePath = $"{stringPath}";
if (!System.IO.Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
var saveName = filePath + file.FileName;
using (FileStream fs = System.IO.File.Create(saveName))
{
await file.CopyToAsync(fs);
fs.Flush();
}
return Ok(new { code = "201", msg = "上传成功" });
}
3、使用中间件,限值POST请求最大限值
自定义个一个HttpRequestMiddleware中间件
public class HttpRequestMiddleware
{
private readonly RequestDelegate next;
private IWebHostEnvironment environment;
private readonly ILogger<HttpRequestMiddleware> _logger;
public HttpRequestMiddleware(RequestDelegate next, IWebHostEnvironment environment, ILogger<HttpRequestMiddleware> logger)
{
this.next = next;
this.environment = environment;
_logger = logger;
}
public async Task Invoke(HttpContext context)
{
try
{
HttpRequest request = context.Request;
if (request.Method.ToLower().Equals("post"))
{
request.EnableBuffering();
Stream stream = request.Body;
if (request.ContentLength.Value/1024/1024>=801)
{
await context.Response.WriteAsync("POST请求数据不得超过801M");
return;
}
await next.Invoke(context);
}
await next.Invoke(context);
}
catch (Exception ex)
{
await HandleError(context, ex);
}
}
private async Task HandleError(HttpContext context, Exception ex)
{
context.Response.StatusCode = 500;
context.Response.ContentType = "text/json;charset=utf-8;";
string errorMsg = $"错误消息:{ex.Message}{Environment.NewLine}错误追踪:{ex.StackTrace}";
//无论是否为开发环境都记录错误日志
_logger.LogError(errorMsg);
//浏览器在开发环境显示详细错误信息,其他环境隐藏错误信息
if (environment.IsDevelopment())
{
await context.Response.WriteAsync(errorMsg);
}
else
{
await context.Response.WriteAsync("抱歉,服务端出错了");
}
}
}
Configure中,使用当前中间件
app.UseMiddleware<HttpRequestMiddleware>();