Minify HTML with .NET MVC ActionFilter

Jak
Jak
Member
352 Points
151 Posts

Hi,

I am working with mvc to remove the unwanted space from the remder html pages. How can I do in action filter?

Views: 8159
Total Answered: 2
Total Marked As Answer: 0
Posted On: 05-Nov-2015 00:32

Share:   fb twitter linkedin
Answers
Smith
Smith
Participant
360 Points
110 Posts
     

Hi Jak,

You can do as , create a class:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
namespace filternamespace.CommonClass
{
public class WhiteSpaceFilter : Stream
{
private Stream _shrink;
private Func<string, string> _filter;
public WhiteSpaceFilter(Stream shrink, Func<string, string> filter)
{
_shrink = shrink;
_filter = filter;
}
 
public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return true; } }
public override bool CanWrite { get { return true; } }
public override void Flush() { _shrink.Flush(); }
public override long Length { get { return 0; } }
public override long Position { get; set; }
public override int Read(byte[] buffer, int offset, int count)
{
return _shrink.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _shrink.Seek(offset, origin);
}
public override void SetLength(long value)
{
_shrink.SetLength(value);
}
public override void Close()
{
_shrink.Close();
}
public override void Write(byte[] buffer, int offset, int count)
{
// capture the data and convert to string
byte[] data = new byte[count];
Buffer.BlockCopy(buffer, offset, data, 0, count);
string s = Encoding.Default.GetString(buffer);
// filter the string
s = _filter(s);
// write the data to stream
byte[] outdata = Encoding.Default.GetBytes(s);
_shrink.Write(outdata, 0, outdata.GetLength(0));
}
}
public class WhitespaceFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;
response.Filter = new WhiteSpaceFilter(response.Filter, s =>
{
s = Regex.Replace(s, @"\s+", " ");
s = Regex.Replace(s, @"\s*\n\s*", "\n");
s = Regex.Replace(s, @"\s*\>\s*\<\s*", "><");
s = Regex.Replace(s, @"<!--(.*?)-->", ""); //Remove comments
// single-line doctype must be preserved
var firstEndBracketPosition = s.IndexOf(">");
if (firstEndBracketPosition >= 0)
{
s = s.Remove(firstEndBracketPosition, 1);
s = s.Insert(firstEndBracketPosition, ">");
}
return s;
});
}
} 
}

And then use in controller as:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using filternamespace.CommonClass;
namespace testproject.Controllers
{
[WhitespaceFilter]
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{ 
return View();
}
}
}

 

 

Posted On: 05-Nov-2015 04:37
Rahul Maurya
Rahul M...
Moderator
1170 Points
210 Posts
     

Hi Smith,

Above code works well but after removing the java script one line comment code (//line code). But I think take time to minify every time if the user request page.

You can do html minify at time of publish. For this you have to change publish profile as:

<?xml version="1.0" encoding="utf-8"?>
<!--
This file is used by the publish/package process of your Web project. You can customize the behavior of this process
by editing this MSBuild file. In order to learn more about this please visit https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="https://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<AspnetCompileMergeIntermediateOutputPath>c:\publish\</AspnetCompileMergeIntermediateOutputPath>
<WebPublishMethod>FileSystem</WebPublishMethod>
<LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
<LastUsedPlatform>Any CPU</LastUsedPlatform>
<SiteUrlToLaunchAfterPublish />
<LaunchSiteAfterPublish>True</LaunchSiteAfterPublish>
<ExcludeApp_Data>False</ExcludeApp_Data>
<publishUrl>D:\Publish</publishUrl>
<DeleteExistingFiles>True</DeleteExistingFiles>
<PrecompileBeforePublish>True</PrecompileBeforePublish>
<EnableUpdateable>True</EnableUpdateable>
<DebugSymbols>False</DebugSymbols>
<WDPMergeOption>DonotMerge</WDPMergeOption>
</PropertyGroup>
<!-- Minify the HTML-->
<Target Name="CustomAction" AfterTargets="CopyAllFilesToSingleFolderForPackage">
<Message Text="Minifying files....." />
<Exec Command="C:\htmlminifier.exe $(_PackageTempDir)" IgnoreExitCode="true" />
</Target>
</Project>

And htmlminifier.exe can b e download from link

https://github.com/deanhume/html-minifier

Posted On: 05-Nov-2015 23:11
banner

Blog

Active User (2)

 Log In to Chat