利用ResultFilter实现asp.net mvc 页面静态化
为了提高网站性能、和网站的负载能力,页面静态化是一种有效的方式,这里对于asp.net mvc3 构架下的网站,提供一种个人认为比较好的静态话方式。
实现原理是通过mvc提供的过滤器扩展点实现页面内容的文本保存,直接上代码:
1 public class StaticFileWriteFilterAttribute : FilterAttribute, IResultFilter 2 { 3 public void OnResultExecuted(ResultExecutedContext filterContext) 4 { 5 6 } 7 8 public void OnResultExecuting(ResultExecutingContext filterContext) 9 { 10 filterContext.HttpContext.Response.Filter = new StaticFileWriteResponseFilterWrapper(filterContext.HttpContext.Response.Filter, filterContext); 11 } 12 13 class StaticFileWriteResponseFilterWrapper : System.IO.Stream 14 { 15 private System.IO.Stream inner; 16 private ControllerContext context; 17 public StaticFileWriteResponseFilterWrapper(System.IO.Stream s,ControllerContext context) 18 { 19 this.inner = s; 20 this.context = context; 21 } 22 23 public override bool CanRead 24 { 25 get { return inner.CanRead; } 26 } 27 28 public override bool CanSeek 29 { 30 get { return inner.CanSeek; } 31 } 32 33 public override bool CanWrite 34 { 35 get { return inner.CanWrite; } 36 } 37 38 public override void Flush() 39 { 40 inner.Flush(); 41 } 42 43 public override long Length 44 { 45 get { return inner.Length; } 46 } 47 48 public override long Position 49 { 50 get 51 { 52 return inner.Position; 53 } 54 set 55 { 56 inner.Position = value; 57 } 58 } 59 60 public override int Read(byte[] buffer, int offset, int count) 61 { 62 return inner.Read(buffer, offset, count); 63 } 64 65 public override long Seek(long offset, System.IO.SeekOrigin origin) 66 { 67 return inner.Seek(offset, origin); 68 } 69 70 public override void SetLength(long value) 71 { 72 inner.SetLength(value); 73 } 74 75 public override void Write(byte[] buffer, int offset, int count) 76 { 77 inner.Write(buffer, offset, count); 78 try 79 { 80 string p = context.HttpContext.Server.MapPath(HttpContext.Current.Request.Path); 81 82 if (Path.HasExtension(p)) 83 { 84 string dir = Path.GetDirectoryName(p); 85 if (!Directory.Exists(dir)) 86 { 87 Directory.CreateDirectory(dir); 88 } 89 if (File.Exists(p)) 90 { 91 File.Delete(p); 92 } 93 File.AppendAllText(p, System.Text.Encoding.UTF8.GetString(buffer)); 94 } 95 } 96 catch 97 { 98 99 } 100 } 101 } 102 }
我们的类StaticFileWriteFilterAttribute实现了IResultFilter,这个接口有两个方法,OnResultExecuted和OnResultExecuting,其中OnResultExecuting是在controller中的action代码执行完毕后,但viewresult执行之前(即页面内容生成之前)执行;OnResultExecuted方法是在viewresult执行之后(即页面内容生成之后)执行。
我们在页面生成之前将StaticFileWriteResponseFilterWrapper类注册给Response对象的Filter属性,这里使用包装类可以在没有副作用的情况下注入页面内容静态化的代码,对于处理业务逻辑的action是透明的。