我使用C#
Asp.net 4,
我在Global.asax中有这个脚本.我能够gzip所有的asp.net页面,但不是
JavaScripts和CSS.
我想知道是否有可能直接在我的网络应用程序中压缩CSS和JS,或者它可能只在IIS中.如果可能,请指出我在我的代码中遗漏的内容.
谢谢
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
string acceptEncoding = app.Request.Headers["Accept-Encoding"];
Stream prevUncompressedStream = app.Response.Filter;
if (!(app.Context.CurrentHandler is Page ||
app.Context.CurrentHandler.GetType().Name == "SyncSessionlessHandler") ||
app.Request["HTTP_X_MICROSOFTAJAX"] != null)
return;
if (acceptEncoding == null || acceptEncoding.Length == 0)
return;
acceptEncoding = acceptEncoding.ToLower();
// if (acceptEncoding.Contains("deflate") || acceptEncoding == "*")
if (acceptEncoding.Contains("gzip") || acceptEncoding == "*")
{
// gzip
app.Response.Filter = new GZipStream(prevUncompressedStream,
CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "gzip");
}
// else if (acceptEncoding.Contains("gzip"))
else if (acceptEncoding.Contains("deflate"))
{
// defalte
app.Response.Filter = new DeflateStream(prevUncompressedStream,
CompressionMode.Compress);
app.Response.AppendHeader("Content-Encoding", "deflate");
}
}
最佳答案 你确定* .css和* .js是由ASP.NET运行时处理的吗?它们不是默认情况下,例如,您必须在web.config中将runAllManagedModulesForAllRequests设置为true.
另外,为什么不依赖IIS内置压缩?