Click here to Skip to main content
15,881,139 members
Articles / Web Development / ASP.NET
Tip/Trick

Reduce ASP.NET Page Output Size

Rate me:
Please Sign up or sign in to vote.
4.31/5 (7 votes)
26 Feb 2010CPOL2 min read 28.8K   7   6
Introduction...
Introduction

There are several techniques available to reduce ASP.NET page output size. Today we will discuss two interesting techniques among them.

HTTP Compression

This is a cool technique to reduce page size by compressing HTTP response stream. This feature is available as a part of IIS6.0 and onwards. Generally output of ASP.NET page is in text format which travels from IIS to client browser. Don’t get disappointed, HTTP Compression features can be achieved in ASP.Net application hosted in IIS 5.1 also. Only difference is, we have to write little line of codes instead. Do the following steps in “Global.asax” to encode the page output.

Step1: Include the name space “System.IO.Compression

Step2: Write following function to see, whether HTTP compression is supported by client browser.

C#
public bool IsCompressionAllowed()
{
  //Browser supported encoding format
  string AcceptEncoding = HttpContext.Current.Request.Headers"[Accept-Encoding"];

  if (!string.IsNullOrEmpty(AcceptEncoding))
  {
     if(AcceptEncoding.Contains("gzip") || AcceptEncoding.Contains("deflate"))
     return true; ////If browser supports encoding
   }

  return false;
}


Step3: Add the event handler “Application_AuthenticateRequest” and write following code.

C#
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {
            HttpResponse Response = HttpContext.Current.Response;
           
            // If client browser supports HTTP compression
            if (IsCompressionAllowed()) 
            {
                // Browser supported encoding format              
                string AcceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"]; 
                // If client browser supports both "deflate" and "gzip" compression, 
               // Then we will consider "deflate" first , because it is
               // more efficient than "gzip"
                if (AcceptEncoding.Contains("deflate"))
                {
                    Response.Filter = new DeflateStream(Response.Filter,
                                               CompressionMode.Compress);
                    Response.AppendHeader("Content-Encoding", "deflate");
                }
                else
                {
                    Response.Filter = new GZipStream(Response.Filter,CompressionMode.Compress);
                    Response.AppendHeader("Content-Encoding", "gzip");
                }
            }

            // Allow proxy servers to cache encoded and unencoded versions separately
            Response.AppendHeader("Vary", "Content-Encoding");

        }


Above code will compress HTTP response based on the compression format supported by browser. Now if we run a sample application and track the http response through Fiddler, we can see that, the response has come to browser in “deflate” format and the entity size is 1765 byte.


If we remove the compression part from Global.asax and run the same application to see HTTP Response in fiddler, we can see the output is in "No Compression" format and the entity size is 106861 byte.


Just compare the page size 1,765 byte vs. 106861 byte and understand how drastically the page size has come down to 1765 byte with “HTTP Compression”.


SessionPageStatePersister

ASP.NET persistence mechanism store view state data in HiddenFieldPageStatePersister class , which in turn maintain data in a hidden text box. This mechanism is well known but specially creates problem when view state is not maintained carefully. Page with larger size of view state increase the downtime and affects the performance. Using “SessionPageStatePersister” we can store viewstate in session also. Storing view state in session drastically reduces page size and expedites performance. See below the steps involved.

Step1:Add a class named PageController inherited from “Page” class.

C#
public class PageController : Page
{
    protected override PageStatePersister PageStatePersister
    {
        get
        {
            // Store view state in session
            return new SessionPageStatePersister(this);
        }
    }
}


Step2:Make sure all ASP.NET page must derive from above class.

C#
public partial class Default : PageController
   {
       protected void Page_Load(object sender, EventArgs e)
       {
            /// Code will come here
       }


That’s all, if you browse your page and check the view state. You can see view state size has almost come down to half. Below is the view state of a page displaying 1000 records in a grid and each record is pertaining 5 columns.
<input type="hidden" value="/wEPaA8FDzhjYzdmOTg5ZTEyZGRhYxgBBQdHcmRVc2VyDzwrAAoBCAIBZJVttOvUuwS2wCkalf3GpRmGTzHN" />


While implementing SessionPageStatePersister we must consider following parameters


1.Since viewstate is maintaining in session so numerous access to
the application might degrade the performance.

2.Viewstate info will still persist in the memory after user logs
out or leaves the page. Memory will get release when session time
out occurs

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Reputed MNC in Kolkata
India India
Bibhas has 8 years of extensive experience in application development with exposure to business requirement study, system analysis and designing, coding ,testing,
implementation, end user training and client Interaction.

He was the part of application development team and worked for industry leading organizations like "ConocoPhillips", "Abbey National Bank" and “DHL".

Posses sound experience as a technical architect and all part of software development lifecycle.

His interest includes in Microsoft Technologies (ASP.NET 3.5 & SQL Server), Design Pattern and wide variety of internet technologies like AJAX, JQUERY etc.

Comments and Discussions

 
GeneralReason for my vote of 5 ultra-useful! Pin
h325-Jan-11 6:35
h325-Jan-11 6:35 
Generalproblem with javascript Pin
nicholkas8-Jul-10 19:45
nicholkas8-Jul-10 19:45 
GeneralNo difference seen in Fiddler Pin
kannankeril25-Feb-10 20:11
kannankeril25-Feb-10 20:11 
I have added the code but it does not seem to reduce the number of bytes coming over the network. When I step thru the code, it is using Deflate compression but Fiddler does not show any difference in resulting file size.

Do I have to configure IIS 5.1 specifically to support compression?
GeneralRe: No difference seen in Fiddler Pin
Bibhas Paul26-Feb-10 17:41
Bibhas Paul26-Feb-10 17:41 
Generaltypo Pin
howard birch23-Feb-10 4:31
howard birch23-Feb-10 4:31 
GeneralRe: typo Pin
Bibhas Paul23-Feb-10 6:42
Bibhas Paul23-Feb-10 6:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.