我正在使用以下代码来快速缩小我的CSS:
namespace MyCMS.Modules
{
public class CSSModule : IHttpModule
{
void IHttpModule.Dispose()
{
throw new NotImplementedException();
}
void IHttpModule.Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpContext context = app.Context;
if (app.Request.RawUrl.Contains(".css"))
{
context.Response.Filter = new CSSFilter(app.Response.Filter);
}
}
private class CSSFilter : Stream
{
public CSSFilter(Stream sink) { _sink = sink; }
private Stream _sink;
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() { _sink.Flush(); }
public override long Length { get { return 0; } }
private long _position;
public override long Position
{
get { return _position; }
set { _position = value; }
}
public override int Read(byte[] buffer, int offset, int count) { return _sink.Read(buffer, offset, count); }
public override long Seek(long offset, SeekOrigin origin) { return _sink.Seek(offset, origin); }
public override void SetLength(long value) { _sink.SetLength(value); }
public override void Close() { _sink.Close(); }
public override void Write(byte[] buffer, int offset, int count)
{
byte[] data = new byte[count];
Buffer.BlockCopy(buffer, offset, data, 0, count);
string html = System.Text.Encoding.Default.GetString(buffer);
html = Yahoo.Yui.Compressor.CssCompressor.Compress(html,0, Yahoo.Yui.Compressor.CssCompressionType.Hybrid, true);
byte[] outdata = System.Text.Encoding.Default.GetBytes(html);
_sink.Write(outdata, 0, outdata.GetLength(0));
}
}
}
}
问题是,GZip的CRC(在服务器上启用)失败。
我确实理解为什么它失败了,因为文件内容是X
,现在是Y
(缩小),
并且原始CRC计算为X
,而不是Y
。
我该怎么做才能解决这个问题?
答案 0 :(得分:0)
我用CSSModule创建了一个示例MVC应用程序,
使用out模块,Site.css大小为~6kb。
使用模块Site.css size~1kb。
可能会帮助你。