How to enable gzip compression in mvc
Microsoft Net Framework

How to enable gzip compression in mvc

1) Code in Global Asax


add folowing name spaces

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.IO;
using System.IO.Compression;
using System.Threading;


        void Application_PreRequestHandlerExecute(object sender, EventArgs e)
            var app = sender as HttpApplication;
            if (app != null)
                string acceptEncoding = app.Request.Headers["Accept-Encoding"];
                Stream prevUncompressedStream = app.Response.Filter;

                if (!(app.Context.CurrentHandler is Page ||
                      app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
                    app.Request["HTTP_X_MICROSOFTAJAX"] != null)

                if (string.IsNullOrEmpty(acceptEncoding))

                acceptEncoding = acceptEncoding.ToLower();

                if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
                    // defalte
                    app.Response.Filter = new DeflateStream(prevUncompressedStream,
                    app.Response.AppendHeader("Content-Encoding", "deflate");
                else if (acceptEncoding.Contains("gzip"))
                    // gzip
                    app.Response.Filter = new GZipStream(prevUncompressedStream,
                    app.Response.AppendHeader("Content-Encoding", "gzip");

2- Code add in web.config

    <httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
      <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/x-javascript" enabled="true" />
        <add mimeType="*/*" enabled="false" />
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/javascript" enabled="true" />
        <add mimeType="*/*" enabled="false" />

Share This with your friend by choosing any social account

Upcoming Articles
You may also read following recent Post
Copyright Future Minutes © 2015- 2024 All Rights Reserved.   Terms of Service  |   Privacy Policy |  Contact US|  Pages|  Whats new?
Update on: Dec 20 2023 05:10 PM