添加以下中间件即可
app.Use(async (context, next) => { var token = context.RequestAborted; var response = context.Response; IFileProvider fileProvider = new PhysicalFileProvider(@"E:"); // 文件所在根目录 IFileInfo file = fileProvider.GetFileInfo(@"神话26.mp4"); // 文件相对根目录所在地址 if (!file.Exists) { await next(); return; } var suffix = ".mp4"; var provider = new FileExtensionContentTypeProvider(); var memi = provider.Mappings[suffix]; response.ContentType = memi; response.Headers.Add(" Content-Disposition ", " attachment;filename= " + "神话26.mp4"); response.ContentLength = file.Length; // 提供文件地址即可发送文件 //await response.SendFileAsync(@"E:神话26.mp4", token); // 提供文件信息即可发送文件 //await response.SendFileAsync(file, token); // 基于body发送文件,好处是可以控制下载速度 var fs = file.CreateReadStream(); using (System.IO.BinaryReader br = new System.IO.BinaryReader(fs)) { await response.Body.FlushAsync(); var kbs = 1024f * 2 / 10; while (fs.Position < fs.Length) { if (token.IsCancellationRequested) break; byte[] bytes = br.ReadBytes((int)Math.Truncate(1024 * kbs)); await response.Body.WriteAsync(bytes, 0, bytes.Length); await response.Body.FlushAsync(); System.Threading.Thread.Sleep(100); } await response.Body.FlushAsync(); } });