Asp.Net MVC 页面代码压缩筛选器
首先定义以下筛选器,用于代码压缩。
/*页面压缩 筛选器*/
public class WhiteSpaceFilter : Stream
{
private Stream _shrink;
private Func<string, string> _filter; public WhiteSpaceFilter(Stream shrink, Func<string, string> filter)
{
_shrink = shrink;
_filter = filter;
} public override bool CanRead { get { return true; } }
public override bool CanSeek { get { return true; } }
public override bool CanWrite { get { return true; } }
public override void Flush() { _shrink.Flush(); }
public override long Length { get { return ; } }
public override long Position { get; set; }
public override int Read(byte[] buffer, int offset, int count)
{
return _shrink.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return _shrink.Seek(offset, origin);
}
public override void SetLength(long value)
{
_shrink.SetLength(value);
}
public override void Close()
{
_shrink.Close();
} public override void Write(byte[] buffer, int offset, int count)
{
// capture the data and convert to string
byte[] data = new byte[count];
Buffer.BlockCopy(buffer, offset, data, , count);
string s = Encoding.GetEncoding("gb2312").GetString(buffer); // filter the string
s = _filter(s); // write the data to stream
byte[] outdata = Encoding.GetEncoding("gb2312").GetBytes(s);
_shrink.Write(outdata, , outdata.GetLength());
}
} public class WhitespaceFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;
response.Filter = new WhiteSpaceFilter(response.Filter, s =>
{
s = Regex.Replace(s, @"\s+(?=<)|\s+$|(?<=>)\s+|<!--.+-->|[ ]+//.+\n|/\*.+\*/|\n", ""); //single-line doctype must be preserved
var firstEndBracketPosition = s.IndexOf(">");
if (firstEndBracketPosition >= )
{
s = s.Remove(firstEndBracketPosition, );
s = s.Insert(firstEndBracketPosition, ">");
}
return s;
});
}
}
/*页面压缩 筛选器 end*/
在要压缩页面的action上使用。
[WhitespaceFilter]
public ActionResult home()
{
return View();
}
我们可以自行修改替换规则,以达到最优化。
s = Regex.Replace(s, @"\s+(?=<)|\s+$|(?<=>)\s+|<!--.+-->|[ ]+//.+\n|/\*.+\*/|\n", "");