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)

posted @   无心々菜  阅读(79)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示