You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.8 KiB

  1. using Microsoft.Ajax.Utilities;
  2. using System;
  3. using System.IO;
  4. using System.Web;
  5. using System.Web.Caching;
  6. public class MinifyHandler : IHttpHandler
  7. {
  8. public void ProcessRequest(HttpContext context)
  9. {
  10. string file = context.Server.MapPath(context.Request.CurrentExecutionFilePath);
  11. string ext = Path.GetExtension(file);
  12. if (context.IsDebuggingEnabled)
  13. {
  14. context.Response.TransmitFile(file);
  15. }
  16. else
  17. {
  18. Minify(context.Response, file, ext);
  19. }
  20. SetHeaders(context.Response, file, ext);
  21. }
  22. private static void SetHeaders(HttpResponse response, string file, string ext)
  23. {
  24. response.ContentType = ext == ".css" ? "text/css" : "text/javascript";
  25. response.Cache.SetLastModified(File.GetLastWriteTimeUtc(file));
  26. response.Cache.SetValidUntilExpires(true);
  27. response.Cache.SetExpires(DateTime.Now.AddYears(1));
  28. response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
  29. response.Cache.SetVaryByCustom("Accept-Encoding");
  30. response.AddCacheDependency(new CacheDependency(file));
  31. }
  32. private static void Minify(HttpResponse response, string file, string ext)
  33. {
  34. string content = File.ReadAllText(file);
  35. Minifier minifier = new Minifier();
  36. if (ext == ".css")
  37. {
  38. CssSettings settings = new CssSettings() { CommentMode = CssComment.None };
  39. response.Write(minifier.MinifyStyleSheet(content, settings));
  40. }
  41. else if (ext == ".js")
  42. {
  43. CodeSettings settings = new CodeSettings() { PreserveImportantComments = false };
  44. response.Write(minifier.MinifyJavaScript(content, settings));
  45. }
  46. }
  47. public bool IsReusable
  48. {
  49. get { return false; }
  50. }
  51. }