【发布时间】:2019-06-26 05:27:38
【问题描述】:
我想在我的Asp.Net 网站上压缩回复。我写了这段代码:
public static void CompressPage(HttpRequest Request, HttpResponse Response)
{
string acceptEncoding = Request.Headers["Accept-Encoding"];
Stream prevUncompressedStream = Response.Filter;
if (acceptEncoding.IsEmpty())
{
return;
}
acceptEncoding = acceptEncoding.ToLower();
if (acceptEncoding.Contains("gzip"))
{
Response.Filter = new GZipStream(prevUncompressedStream, CompressionMode.Compress);
Response.AppendHeader("Content-Encoding", "gzip");
}
else if (acceptEncoding.Contains("deflate"))
{
Response.Filter = new DeflateStream(prevUncompressedStream, CompressionMode.Compress);
Response.AppendHeader("Content-Encoding", "deflate");
}
}
并称之为Page_Load事件:
protected void Page_Load(object sender, EventArgs e)
{
...
ZipHtmlPage.CompressPage(Request, Response);
}
问题是当我在Page_Load 中运行带有和不带有上述代码的代码时,响应的大小不会改变。
问题出在哪里?
谢谢
编辑 1)
我认为"Content-Encoding", "gzip" 不会添加到标题中:
不知道为什么?
编辑 2)
当我使用HttpModule 进行http 压缩时:
public class CompressModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
}
private void Application_BeginRequest(Object source, EventArgs e)
{
HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-Encoding", "gzip");
}
public void Dispose()
{
}
}
我在每一页都有这个:
【问题讨论】:
-
谷歌搜索
asp.net enable gzip有许多可能的想法可以尝试。您尝试过其中任何一个吗? -
@mjwills 我不想用
IIS这样做。我想压缩几页 -
建议在 IIS 级别上进行,而不是构建自己的中间件。
-
是的,我非常同意@ArtemIgnatovich 的观点,重新发明轮子不是日常工作,当我们可以利用 WebServer 中提供的功能时,不建议您自己实现。
标签: c# asp.net gzip response http-compression