Tomas Kubes
Tomas Kubes

Reputation: 25108

How to configure HTML Minification in ASP.NET MVC

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

I installed Nuget

Install-Package WebMarkupMin.Mvc

Then I add Filter Attributte:

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

But the HTML minification does not work.

Nuget Installation add few lines to the 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.

Am I missing something?

Upvotes: 4

Views: 6917

Answers (3)

Andrey Taritsyn
Andrey Taritsyn

Reputation: 1286

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

<?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:

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

Upvotes: 11

Ronald Hobbs
Ronald Hobbs

Reputation: 11

You need to add the following to enable the webextensions (from the 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.

Upvotes: 1

Alexander Dayan
Alexander Dayan

Reputation: 2924

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

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

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.

Add this attribute to the controller methods

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

and we're done.

Upvotes: 1

Related Questions