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)