ASP.NET Core中间件

WebMarkupMin可以做什么:

运行时最小化html、css、js(去除空格、注释...)
对HTTP启用压缩(GZip、Deflate、Brotli..)

使用步骤:

添加Nuget包:

<PackageReference Include="WebMarkupMin.AspNet.Brotli" Version="2.8.1" />
<PackageReference Include="WebMarkupMin.AspNetCore2" Version="2.8.8" />
<PackageReference Include="WebMarkupMin.NUglify" Version="2.8.10" />

ConfigureServices()方法中添加:

 services.AddWebMarkupMin(
                           options =>
                {
                    options.AllowMinificationInDevelopmentEnvironment = true;//本地html调试必须设置为true,否则不生效
                    options.AllowCompressionInDevelopmentEnvironment = true;//本地API调试必须设置为true,否则不生效
                    options.DefaultEncoding = Encoding.UTF8;
                })
            //Html压缩
            .AddHtmlMinification(options =>
            {
                HtmlMinificationSettings settings = options.MinificationSettings;
                settings.RemoveRedundantAttributes = true;
                settings.RemoveHttpProtocolFromAttributes = true;
                settings.RemoveHttpsProtocolFromAttributes = true;
                settings.RemoveTagsWithoutContent = true;
                settings.RemoveEmptyAttributes = true;
                settings.RemoveHtmlComments = true;
                settings.RemoveHtmlCommentsFromScriptsAndStyles = true;
                settings.RemoveJsProtocolFromAttributes = true;
                settings.MinifyEmbeddedJsCode = false;
                settings.MinifyEmbeddedCssCode = true;
                settings.MinifyEmbeddedJsonData = false;
                settings.MinifyInlineCssCode = true;//页面内css压缩
                settings.MinifyInlineJsCode = false;//页面内js压缩
                options.CssMinifierFactory = new NUglifyCssMinifierFactory();
                options.JsMinifierFactory = new NUglifyJsMinifierFactory();
            })
            //Http压缩
            .AddHttpCompression(options =>
            {
                options.CompressorFactories = new List<ICompressorFactory>
                {
                    new BrotliCompressorFactory(new BrotliCompressionSettings
                    {
                         Level = (int)CompressionLevel.Fastest
                    })
                    ,
                    new GZipCompressorFactory(new GZipCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    })
                    ,
                    new DeflateCompressorFactory(new DeflateCompressionSettings
                    {
                        Level = CompressionLevel.Fastest
                    })
                };
            })
            ;

Configure方法中添加:

app.UseWebMarkupMin();

参考:
https://andrewlock.net/html-minification-using-webmarkupmin-in-asp-net-core/

原文地址:https://www.cnblogs.com/fanfan-90/p/13896356.html