Created
December 22, 2011 15:24
-
-
Save nicwise/1510675 to your computer and use it in GitHub Desktop.
CSS parsing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
using System.Text; | |
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Text; | |
using System.Threading; | |
using System.Web; | |
using System.Web.Caching; | |
namespace UmgCommon.CDN | |
{ | |
/* | |
* | |
* Re parses the CSS to add in the cache key | |
* | |
* add this into the web.config | |
* | |
* <add name="CssRewriter" verb="*" path="*.css" preCondition="integratedMode" type="UmgCommon.CDN.CssRewriteHandler, UmgCommon" /> | |
* add it in system.webServer -> handlers | |
* | |
* */ | |
public class CssRewriteHandler : IHttpHandler | |
{ | |
public bool IsReusable { get { return true; } } | |
public void ProcessRequest(HttpContext context) | |
{ | |
string filename = context.Request.PhysicalPath; | |
//remove the X | |
if (filename.EndsWith("x")) | |
{ | |
filename = filename.Substring(0, filename.Length - 1); | |
} | |
if (!File.Exists(filename)) | |
{ | |
context.Response.StatusCode = 404; | |
return; | |
} | |
string css = File.ReadAllText(filename); | |
string suffix = ""; | |
if (CDNHelper.IsCDNEnabled) | |
{ | |
object res = context.Cache["csscache|" + filename]; | |
if (res != null) | |
{ | |
css = res.ToString(); | |
context.Response.Write("/* Processed by the CDN CSS rewriter from cache */\n"); | |
} | |
else | |
{ | |
Stopwatch sw = new Stopwatch(); | |
sw.Start(); | |
suffix = CDNHelper.UniqueId; | |
css = css.Replace(".jpg", ".jpg" + suffix) | |
.Replace(".png", ".png" + suffix) | |
.Replace(".gif", ".gif" + suffix); | |
sw.Stop(); | |
context.Cache.Add("csscache|" + filename, css, new CacheDependency(filename), DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration, CacheItemPriority.Normal,null); | |
context.Response.Write(string.Format("/* Processed by the CDN CSS rewriter in {0}ms */\n", sw.ElapsedMilliseconds)); | |
} | |
} | |
context.Response.Write(css); | |
context.Response.ContentType = "text/css"; | |
context.Response.AddFileDependency(filename); | |
HttpCachePolicy cache = context.Response.Cache; | |
cache.SetCacheability(HttpCacheability.Public); | |
if (CDNHelper.IsCDNEnabled) | |
{ | |
cache.SetETag(suffix); | |
} | |
cache.SetLastModifiedFromFileDependencies(); | |
cache.SetMaxAge(TimeSpan.FromMinutes(60)); | |
cache.SetRevalidation(HttpCacheRevalidation.AllCaches); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment