Bundling and Minification in MVC

Bundling and Minification in MVC

In this post, Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.) Bundling and minification are two techniques you can use in ASP.NET 4.5 or above to improve request load time. 

BundleConfig.cs

 

public static void RegisterBundles(BundleCollection bundles)
        {
            bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                        "~/Scripts/jquery-{version}.js"));

            bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                        "~/Scripts/jquery.validate*"));

            // Use the development version of Modernizr to develop with and learn from. Then, when you're
            // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
            bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                        "~/Scripts/modernizr-*"));

            bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                      "~/Scripts/bootstrap.js",
                      "~/Scripts/respond.js","~/Scripts/event.js"));

            bundles.Add(new StyleBundle("~/Content/css").Include(
                      "~/Content/bootstrap.css",
                      "~/Content/site.css"));
            BundleTable.EnableOptimizations = true;
        }

RouteConfig.cs

 

public static void RegisterRoutes(RouteCollection routes)
        {
            BundleTable.EnableOptimizations = true;
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
            routes.MapRoute(
            name: "sitemap",
            url: "sitemap.xml",
            defaults: new { controller = "Home", action = "sitemap" }
        );
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }

FilterConfig.cs

 

 public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
    class EtagFilter : ActionFilterAttribute
    {
        private DateTime _currentTime = DateTime.Now;

        private string _currentEtag = string.Empty;
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {

            var httpContext = filterContext.RequestContext.HttpContext;
            string eTag = httpContext.Request.Headers["If-None-Match"];
            string responseETag = GetEtag();
            if (!string.IsNullOrEmpty(eTag))
            {
                if (eTag.Equals(responseETag))
                {
                    filterContext.HttpContext.Response.StatusCode = 304;

                    filterContext.HttpContext.Response.StatusDescription = "Not Modified";
                }

                return;
            }

            httpContext.Response.AddHeader("ETag", responseETag);
        }
        private string GetEtag()
        {
            if (_currentTime <= DateTime.Now.AddSeconds(10))
            {
                _currentEtag = GenerateEtag();
                return _currentEtag;
            }

            _currentEtag = GenerateEtag();

            return _currentEtag;
        }

        private string GenerateEtag()
        {
            return Guid.NewGuid().ToString().Substring(0, 20);
        }
    }

Web.config

 <httpProtocol>
      <customHeaders>
        <clear />
        <remove name="X-Powered-By" />
        <remove name="X-Powered-By-Plesk" />
        <add name="Transfer-Encoding: chunked" />
      </customHeaders>
    </httpProtocol>

_Layout.cshtml

 

 @Styles.Render("~/Content/css") 
@Scripts.Render("~/bundles/modernizr") 
@Scripts.Render("~/bundles/jquery")

Output

 

<link href="/Content/css?v=MPPPiGFOcsEC7dgGAMkxW-oe1ajI6SxTIx5z9izAXwk1" rel="stylesheet"/>
 <script src="/bundles/modernizr?v=wBEWDufH_8Md-Pbioxomt90vm6tJN2Pyy9u9zHtWsPo1"></script>
 <script src="/bundles/jquery?v=hMTR6S5uitG_pTi_gAkAnslTfg4guLwzTBNa9TcoD3s1"></script>

 

2020-02-22