Monday, February 13, 2012

Refresh scripts and CSS in browser after deployment

To refresh browser cache after deployment,one can append the assembly hashcode to the script's url so that scripts and CSS will be fetched from server instead of cache.


  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Reflection;
  7. using System.Text;
  8.  
  9. namespace MvcCommon.Common
  10. {
  11.     public static class HtmlHelpers
  12.     {
  13.         private static int HashCode
  14.         {
  15.             get { return Assembly.GetCallingAssembly().GetHashCode(); }
  16.         }
  17.         private static UrlHelper UrlHelper(HtmlHelper htmlHelper)
  18.         {
  19.             return new UrlHelper(htmlHelper.ViewContext.RequestContext);
  20.         }
  21.         public static HtmlString IncludeCSS(this HtmlHelper htmlHelper, params string[] urls)
  22.         {
  23.             var scripts = new StringBuilder();
  24.             
  25.             urls.ToList().ForEach(x=>{
  26.                 var href=UrlHelper(htmlHelper).Content(string.Format("~/Content/{0}",x))+"?"+HashCode;
  27.                 var script = string.Format("<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />", href);
  28.                 scripts.AppendLine(script);
  29.             });
  30.  
  31.             return new HtmlString(scripts.ToString());
  32.         }
  33.         public static HtmlString IncludeJQueries(this HtmlHelper htmlHelper, params string[] urls)
  34.         {
  35.             var scripts = new StringBuilder();
  36.             
  37.             urls.ToList().ForEach(x=>{
  38.                 var href=UrlHelper(htmlHelper).Content(string.Format("~/Scripts/{0}",x))+"?"+HashCode;
  39.                 var script=string.Format("<script src=\"{0}\" type=\"text/javascript\"></script>",href);
  40.                 scripts.AppendLine(script);
  41.             });
  42.  
  43.             return new HtmlString(scripts.ToString());
  44.         }
  45.     }
  46. }

No comments: