务实直接上代码:
1. 重写FilterModule.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Web; 7 using System.Text.RegularExpressions; 8 using System.IO.Compression; 9 10 namespace Compress.FilterModule11 {12 public class FilterModule : IHttpModule13 {14 public void Dispose()15 {16 //17 }18 19 ///20 /// Init method is only used to register the desired event21 /// 22 /// 23 public void Init(HttpApplication context)24 {25 context.BeginRequest += new EventHandler(context_BeginRequest);26 //context.EndRequest += new EventHandler(context_EndRequest);27 //context.PostRequestHandlerExecute += new EventHandler(context_PostRequestHandlerExecute);28 }29 30 31 ///32 /// Handles the BeginRequest event of the context control.33 /// 34 /// The source of the event.35 /// Theinstance containing the event data.36 void context_BeginRequest(object sender, EventArgs e)37 {38 HttpApplication app = sender as HttpApplication;39 HttpContext context = app.Context;40 if (context.CurrentHandler is System.Web.UI.Page)41 {42 bool isPage = context.CurrentHandler.IsReusable;43 }44 if (app.Request.RawUrl.Contains(".aspx") || app.Request.RawUrl.EndsWith("/"))45 {46 // HttpContext context = app.Context;47 HttpRequest request = context.Request;48 string acceptEncoding = request.Headers["Accept-Encoding"];49 HttpResponse response = context.Response;50 if (!string.IsNullOrEmpty(acceptEncoding))51 {52 acceptEncoding = acceptEncoding.ToUpperInvariant();53 if (acceptEncoding.Contains("GZIP"))54 {55 //var straem = new GZipStream(response.Filter, CompressionMode.Compress);56 response.Filter = new CompressWhitespaceFilter(response.Filter, CompressOptions.GZip);57 response.AppendHeader("Content-encoding", "gzip");58 }59 else if (acceptEncoding.Contains("DEFLATE"))60 {61 response.Filter = new CompressWhitespaceFilter(context.Response.Filter, CompressOptions.Deflate);62 response.AppendHeader("Content-encoding", "deflate");63 }64 }65 response.Cache.VaryByHeaders["Accept-Encoding"] = true;66 }67 }68 69 // Test70 //void context_BeginRequest(object sender, EventArgs e)71 //{72 // HttpApplication application = (HttpApplication)sender;73 // HttpContext context = application.Context;74 // context.Response.ContentType = "text/html";75 // context.Response.Charset = "GB2312";76 // context.Response.ContentEncoding = Encoding.Default;77 // context.Response.Write(" Treatment from HttpModule,Begin...
");78 //}79 80 // Test81 //void context_EndRequest(object sender, EventArgs e)82 //{83 // HttpApplication application = (HttpApplication)sender;84 // HttpContext context = application.Context;85 // context.Response.ContentType = "text/html";86 // context.Response.Charset = "GB2312";87 // context.Response.ContentEncoding = Encoding.Default;88 // context.Response.Write("Treatment from HttpModule,End...
");89 //}90 91 }92 }
2. 处理压缩和匹配自定义过滤 CompressWhitespaceFilter.cs
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.IO; 6 using System.Text; 7 using System.Text.RegularExpressions; 8 using System.IO.Compression; 9 10 namespace Compress.ModuleDemo 11 { 12 public enum CompressOptions 13 { 14 GZip, 15 Deflate, 16 None 17 } 18 19 public class CompressWhitespaceFilter : Stream 20 { 21 StringBuilder responseHtml; 22 const string _cssPattern = "(? ]*href\\s*=\\s*[\\\"\\']?(?[^\"'>\\s]*)[\\\"\\']?[^>]*>)"; 23 const string _jsPattern = "(? ", key, string.Join(",", js[key].ToArray()));326 html = html.Insert(x + num + 1, link + Environment.NewLine);327 328 }329 if (javascript.Count > 0)330 {331 link = string.Format(" ", string.Join(",", javascript.ToArray()));332 html = html.Insert(x + num + 1, link + Environment.NewLine);333 }334 return html;335 }336 337 /// 338 /// Replaces the js in the body. (see ReplaceCss for comments)339 /// 340 /// 341 ///342 public string ReplaceJSInBody(string html)343 {344 Uri baseUri = new Uri(app.Request.Url.AbsoluteUri);345 foreach (Match match in Regex.Matches(html, _jsPattern, RegexOptions.IgnoreCase))346 {347 string linkHtml = match.Groups[0].Value;348 string src = match.Groups[2].Value;349 350 351 Uri uri = new Uri(baseUri, src);352 if (!uri.AbsolutePath.EndsWith(".js") && !uri.AbsolutePath.Contains("WebResource.axd"))353 continue;354 string file = "";355 string path = "";356 if (uri.Host == baseUri.Host)357 {358 if (uri.AbsolutePath.ToLower().StartsWith(app.Context.Request.ApplicationPath.ToLower()))359 {360 int index = uri.AbsolutePath.LastIndexOf("/");361 path = uri.AbsolutePath.Substring(0, index + 1);362 file = uri.AbsolutePath.Substring(index + 1) + (src.Contains("?") ? src.Substring(src.IndexOf("?")) : "");363 }364 else365 file = uri.AbsolutePath + uri.Query;366 }367 else368 file = uri.AbsoluteUri;369 string newLinkHtml = linkHtml.Replace(src, path + "js.axd?files=" + file);370 html = html.Replace(linkHtml, newLinkHtml);371 }372 return html;373 }374 375 }376 }