mvc中压缩html
1 public class WhiteSpaceFilter : Stream 2 { 3 private Stream _shrink; 4 private Func<string, string> _filter; 5 6 public WhiteSpaceFilter(Stream shrink, Func<string, string> filter) 7 { 8 _shrink = shrink; 9 _filter = filter; 10 } 11 12 13 public override bool CanRead { get { return true; } } 14 public override bool CanSeek { get { return true; } } 15 public override bool CanWrite { get { return true; } } 16 public override void Flush() { _shrink.Flush(); } 17 public override long Length { get { return 0; } } 18 public override long Position { get; set; } 19 public override int Read(byte[] buffer, int offset, int count) 20 { 21 return _shrink.Read(buffer, offset, count); 22 } 23 public override long Seek(long offset, SeekOrigin origin) 24 { 25 return _shrink.Seek(offset, origin); 26 } 27 public override void SetLength(long value) 28 { 29 _shrink.SetLength(value); 30 } 31 public override void Close() 32 { 33 _shrink.Close(); 34 } 35 36 public override void Write(byte[] buffer, int offset, int count) 37 { 38 // capture the data and convert to string 39 byte[] data = new byte[count]; 40 Buffer.BlockCopy(buffer, offset, data, 0, count); 41 string s = Encoding.UTF8.GetString(buffer); 42 43 // filter the string 44 s = _filter(s); 45 46 // write the data to stream 47 byte[] outdata = Encoding.UTF8.GetBytes(s); 48 _shrink.Write(outdata, 0, outdata.GetLength(0)); 49 } 50 } 51 /// <summary> 52 /// 压缩html 53 /// </summary> 54 public class WhitespaceFilterAttribute : ActionFilterAttribute 55 { 56 public override void OnActionExecuting(ActionExecutingContext filterContext) 57 { 58 var request = filterContext.HttpContext.Request; 59 var response = filterContext.HttpContext.Response; 60 response.Filter = new WhiteSpaceFilter(response.Filter, s => 61 { 62 s = Regex.Replace(s, @"\s+(?=<)|\s+$|(?<=>)\s+", ""); 63 64 //single-line doctype must be preserved 65 var firstEndBracketPosition = s.IndexOf(">"); 66 if (firstEndBracketPosition >= 0) 67 { 68 s = s.Remove(firstEndBracketPosition, 1); 69 s = s.Insert(firstEndBracketPosition, ">"); 70 } 71 return s; 72 }); 73 } 74 }
写一个basecontrol 当做属性来用