Compressing HTML can eliminate useless spaces in your code, which can increase the load speed and bandwidth of your website. Today let's see how HTML compression is implemented in ASP. NET MVC 3, and we can do this by implementing Actionfilter for HTML compression.
In fact we summarize in the ASP. NET MVC 3 site optimization (i) using Gzip compression This is the method used in this article, mainly to see the implementation of the FilterAttribute class:
Public Class Whitespacefilterattribute : ActionFilterAttribute{ Public Override void OnActionExecuting(ActionExecutingContextFiltercontext) { VarRequest=Filtercontext.HttpContext.Request; VarResponse=Filtercontext.HttpContext.Response;Response.Filter = New Whitespacefilter(Response.Filter,S= {S= Regex.Replace(S, @"\s+ (?=<) |\s+$| (?<=>) \s+ ", ""); Single-line doctype must be preserved VarFirstendbracketposition=S.IndexOf(">"); If (Firstendbracketposition>= 0) { s = S. Remove (firstendbracketposition, 1 s = S. Insert (firstendbracketposition, ">" ); } return s }); }} /span>
Add the Filter property on the Action method when you use it, as follows:
[whitespacefilter]publicactionresultIndex(string ID){return View();}
I mainly modified the regular used by the author, because Huare will also replace the spaces in <pre></pre> and specify the encoding as UTF-8.
This enables HTML compression in ASP. 3, you can download the Whitespacefilter.rar class to try it yourself!
ASP. NET MVC 3 Web site Optimization Summary (vi) Compress HTML