NETCORE 使用中间件做文件服务器
NETCORE 使用中间件做文件服务器
创建net6 webapi 项目
创建中间件类 StaticRequestMiddleware
public class StaticRequestMiddleware { public static string RootPath { get; set; } private readonly RequestDelegate _next; private readonly IConfiguration _configuration; public StaticRequestMiddleware(RequestDelegate next, IConfiguration configuration) { _next = next; _configuration = configuration; RootPath = _configuration.GetSection("PathTiles").Value; } public async Task Invoke(HttpContext context) { var pathExpand = context.Request.Path.Value; var path = RootPath + pathExpand; var responseOriginalBody = context.Response.Body; var memStream = new MemoryStream(); context.Response.Body = memStream; //await _next(context); context.Response.StatusCode = 200; var buffer = FileTools.GetFileStream(path); memStream.WriteAsync(buffer, 0, buffer.Length); memStream.Position = 0; await memStream.CopyToAsync(responseOriginalBody); context.Response.Body = responseOriginalBody; } }
配置文件
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, //"PathTiles": "C:\\TilesPublishServer", "PathTiles": "C:\\Users\\12850\\Desktop", "AllowedHosts": "*" }
注入中间件 Program.cs
app.UseMiddleware<StaticRequestMiddleware>();
访问:https://localhost:7179/1.txt
开启GZIP与Br的压缩
在 Program.cs
builder.Services.Configure<BrotliCompressionProviderOptions>(options => { options.Level = CompressionLevel.Optimal; }); builder.Services.Configure<GzipCompressionProviderOptions>(options => { options.Level = CompressionLevel.Optimal; }); builder.Services.AddResponseCompression(options => { options.EnableForHttps = true; // 添加br与gzip的Provider options.Providers.Add<BrotliCompressionProvider>(); options.Providers.Add<GzipCompressionProvider>(); // 扩展一些类型 (MimeTypes中有一些基本的类型,可以打断点看看) options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[] { "text/html; charset=utf-8", "application/xhtml+xml", "application/atom+xml", "image/svg+xml" }); });
加入到http管道中
app.UseResponseCompression();
引用:https://q.cnblogs.com/q/139267/
引用:.NET, ASP.NET Core, C# 开启gzip和br压缩, 减少wasm,js,css等文件和字符串的传输体积 - 知乎 (zhihu.com)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)