如何在ASP.NET Core中预压缩静态文件

节省CPU和带宽

var mimeTypeProvider = new FileExtensionContentTypeProvider();

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = context =>
    {
        var headers = context.Context.Response.Headers;
        var contentType = headers["Content-Type"];

        if (contentType != "application/x-gzip" && !context.File.Name.EndsWith(".gz"))
        {
            return;
        }

        var fileNameToTry = context.File.Name.Substring(0, context.File.Name.Length - 3);

        if (mimeTypeProvider.TryGetContentType(fileNameToTry, out var mimeType))
        {
            headers.Add("Content-Encoding", "gzip");
            headers["Content-Type"] = mimeType;
        }
    }
});

https://mp.weixin.qq.com/s/yzA-LwHIfTAq3jWS92xEGg

你可能感兴趣的:(Asp.net,Core)