如何在ASP.NET MVC中配置HTML Minification

时间:2021-04-30 04:02:49

I would like to configure HTML minification to my ASP>NET MVC5 web application.

我想将HTML缩小配置到我的ASP> NET MVC5 Web应用程序。

I installed Nuget

我安装了Nuget

Install-Package WebMarkupMin.Mvc

Then I add Filter Attributte:

然后我添加Filter Attributte:

[MinifyHtmlAttribute]
public ActionResult Index()
{           
    return View();
}  

But the HTML minification does not work.

但HTML缩小不起作用。

Nuget Installation add few lines to the web.config:

Nuget安装为web.config添加几行:

<sectionGroup name="webMarkupMin">
      <section name="core" type="WebMarkupMin.Core.Configuration.CoreConfiguration, WebMarkupMin.Core" />
      <section name="webExtensions" type="WebMarkupMin.Web.Configuration.WebExtensionsConfiguration, WebMarkupMin.Web" />
</sectionGroup>

<webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd">
  <core>
    <css>
      <minifiers>
        <add name="NullCssMinifier" displayName="Null CSS Minifier" type="WebMarkupMin.Core.Minifiers.NullCssMinifier, WebMarkupMin.Core" />
        <add name="KristensenCssMinifier" displayName="Mads Kristensen's CSS minifier" type="WebMarkupMin.Core.Minifiers.KristensenCssMinifier, WebMarkupMin.Core" />
      </minifiers>
    </css>
    <js>
      <minifiers>
        <add name="NullJsMinifier" displayName="Null JS Minifier" type="WebMarkupMin.Core.Minifiers.NullJsMinifier, WebMarkupMin.Core" />
        <add name="CrockfordJsMinifier" displayName="Douglas Crockford's JS Minifier" type="WebMarkupMin.Core.Minifiers.CrockfordJsMinifier, WebMarkupMin.Core" />
      </minifiers>
    </js>
    <html whitespaceMinificationMode="Medium" removeHtmlComments="true"
          removeHtmlCommentsFromScriptsAndStyles="true"
          removeCdataSectionsFromScriptsAndStyles="true"
          useShortDoctype="true" useMetaCharsetTag="true"
          emptyTagRenderMode="NoSlash" removeOptionalEndTags="true"
          removeTagsWithoutContent="false" collapseBooleanAttributes="true"
          removeEmptyAttributes="true" attributeQuotesRemovalMode="Html5"
          removeRedundantAttributes="true"
          removeJsTypeAttributes="true" removeCssTypeAttributes="true"
          removeHttpProtocolFromAttributes="false"
          removeHttpsProtocolFromAttributes="false"
          removeJsProtocolFromAttributes="true"
          minifyEmbeddedCssCode="true" minifyInlineCssCode="true"
          minifyEmbeddedJsCode="true" minifyInlineJsCode="true"
          processableScriptTypeList="" minifyKnockoutBindingExpressions="false"
          minifyAngularBindingExpressions="false" customAngularDirectiveList="" />
    <logging>
      <loggers>
        <add name="NullLogger" displayName="Null Logger" type="WebMarkupMin.Core.Loggers.NullLogger, WebMarkupMin.Core" />
        <add name="ThrowExceptionLogger" displayName="Throw exception logger" type="WebMarkupMin.Core.Loggers.ThrowExceptionLogger, WebMarkupMin.Core" />
      </loggers>
    </logging>
  </core>
</webMarkupMin>

The html element was added by me manually according to documentation.

我根据文档手动添加了html元素。

Am I missing something?

我错过了什么吗?

3 个解决方案

#1


11  

Web application may be in debug mode. In order to switch it to release mode you need to edit the Web.config file:

Web应用程序可能处于调试模式。要将其切换到发布模式,您需要编辑Web.config文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    ...
    <system.web>
        <compilation debug="false" ... />
        ...
    </system.web>
    ...
</configuration>

In addition, you can disable dependence on web application mode. Using the following settings:

此外,您可以禁用对Web应用程序模式的依赖性。使用以下设置:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    ...
    <webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd">
        <webExtensions disableMinificationInDebugMode="false"
            disableCompressionInDebugMode="false" />
        ...
    </webMarkupMin>
    ...
</configuration>

#2


1  

So large library with so difficult usage and configuration... Are you sure need all this for just the HTML minification?

如此庞大的图书馆使用和配置如此困难......你确定需要所有这些只是为了缩小HTML吗?

Create a new filter under the Filters subfolder of your project and call it CompactHtmlFilterAttribute Use the following code:

在项目的Filters子文件夹下创建一个新过滤器并将其命名为CompactHtmlFilterAttribute使用以下代码:

public class CompactHtmlFilterAttribute : ActionFilterAttribute
{
    public class WhitespaceFilter : MemoryStream
    {
        private string Source = string.Empty;
        private Stream Filter = null;

        public WhitespaceFilter(HttpResponseBase HttpResponseBase)
        {
            Filter = HttpResponseBase.Filter;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            Source = UTF8Encoding.UTF8.GetString(buffer).Replace("\r", "").Replace("\n", "").Replace("\t", "");
            Filter.Write(UTF8Encoding.UTF8.GetBytes(Source), offset, UTF8Encoding.UTF8.GetByteCount(Source));
        }
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        #if DEBUG
            base.OnActionExecuting(filterContext);
        #else
            try
            {
                filterContext.HttpContext.Response.Filter = new WhitespaceFilter(filterContext.HttpContext.Response);
            }
            catch (Exception) { }
        #endif
    }
}

Pay atention on the #if DEBUG dirrective. HTML will be minified only in release configuration, while on debug the original code will be kept for the better readability.

注意#if DEBUG dirrective。 HTML将仅在发布配置中缩小,而在调试时,将保留原始代码以提高可读性。

Add this attribute to the controller methods

将此属性添加到控制器方法

[CompactHtmlFilter]
public ActionResult Index()
{           
    return View();
}

and we're done.

我们完成了。

#3


1  

You need to add the following to enable the webextensions (from the doc):

您需要添加以下内容以启用webextensions(来自doc):

<webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd">
  …
  <webExtensions enableMinification="true" disableMinificationInDebugMode="true"
     enableCompression="true" disableCompressionInDebugMode="true"
     maxResponseSize="100000" disableCopyrightHttpHeaders="false" />
  …
</webMarkupMin>

Note that it's outside the <core> element.

请注意,它位于 元素之外。

also in your view markup you should have the attribute as:

同样在您的视图标记中,您应该具有以下属性:

[MinifyHtml]

Itshouldn't have the ..Attribute at the end of it.

它最终不应该有......属性。

#1


11  

Web application may be in debug mode. In order to switch it to release mode you need to edit the Web.config file:

Web应用程序可能处于调试模式。要将其切换到发布模式,您需要编辑Web.config文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    ...
    <system.web>
        <compilation debug="false" ... />
        ...
    </system.web>
    ...
</configuration>

In addition, you can disable dependence on web application mode. Using the following settings:

此外,您可以禁用对Web应用程序模式的依赖性。使用以下设置:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    ...
    <webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd">
        <webExtensions disableMinificationInDebugMode="false"
            disableCompressionInDebugMode="false" />
        ...
    </webMarkupMin>
    ...
</configuration>

#2


1  

So large library with so difficult usage and configuration... Are you sure need all this for just the HTML minification?

如此庞大的图书馆使用和配置如此困难......你确定需要所有这些只是为了缩小HTML吗?

Create a new filter under the Filters subfolder of your project and call it CompactHtmlFilterAttribute Use the following code:

在项目的Filters子文件夹下创建一个新过滤器并将其命名为CompactHtmlFilterAttribute使用以下代码:

public class CompactHtmlFilterAttribute : ActionFilterAttribute
{
    public class WhitespaceFilter : MemoryStream
    {
        private string Source = string.Empty;
        private Stream Filter = null;

        public WhitespaceFilter(HttpResponseBase HttpResponseBase)
        {
            Filter = HttpResponseBase.Filter;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            Source = UTF8Encoding.UTF8.GetString(buffer).Replace("\r", "").Replace("\n", "").Replace("\t", "");
            Filter.Write(UTF8Encoding.UTF8.GetBytes(Source), offset, UTF8Encoding.UTF8.GetByteCount(Source));
        }
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        #if DEBUG
            base.OnActionExecuting(filterContext);
        #else
            try
            {
                filterContext.HttpContext.Response.Filter = new WhitespaceFilter(filterContext.HttpContext.Response);
            }
            catch (Exception) { }
        #endif
    }
}

Pay atention on the #if DEBUG dirrective. HTML will be minified only in release configuration, while on debug the original code will be kept for the better readability.

注意#if DEBUG dirrective。 HTML将仅在发布配置中缩小,而在调试时,将保留原始代码以提高可读性。

Add this attribute to the controller methods

将此属性添加到控制器方法

[CompactHtmlFilter]
public ActionResult Index()
{           
    return View();
}

and we're done.

我们完成了。

#3


1  

You need to add the following to enable the webextensions (from the doc):

您需要添加以下内容以启用webextensions(来自doc):

<webMarkupMin xmlns="http://tempuri.org/WebMarkupMin.Configuration.xsd">
  …
  <webExtensions enableMinification="true" disableMinificationInDebugMode="true"
     enableCompression="true" disableCompressionInDebugMode="true"
     maxResponseSize="100000" disableCopyrightHttpHeaders="false" />
  …
</webMarkupMin>

Note that it's outside the <core> element.

请注意,它位于 元素之外。

also in your view markup you should have the attribute as:

同样在您的视图标记中,您应该具有以下属性:

[MinifyHtml]

Itshouldn't have the ..Attribute at the end of it.

它最终不应该有......属性。