我正在使用新的System.Web.Optimization并创建了如下所示的捆绑包:
bundles.Add(New ScriptBundle("~/bundles/BaseJS").Include(
"~/Resources/Core/Javascripts/jquery-1.7.1.js",
"~/Resources/Core/Javascripts/jquery-ui-1.8.16.js",
"~/Resources/Core/Javascripts/jquery.validate.js",
"~/Resources/Core/Javascripts/jquery.validate.unobtrusive.js",
"~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.js"))
在我看来,我已经添加了这个
@System.Web.Optimization.Scripts.Render("~/bundles/BaseJS")
在 fiddler 中,URL带有将来1年的到期标题和文本/JavaScript的内容类型
在web.config中,我有一些gzip的代码可以在静态JS文件上运行,但在缩小的捆绑包上似乎没有。
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00"/>
<remove fileExtension=".js"/>
<mimeMap fileExtension=".js" mimeType="text/javascript"/>
</staticContent>
<urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="true"/>
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
<dynamicTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="text/javascript" enabled="true"/>
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="text/javascript" enabled="true"/>
</staticTypes>
</httpCompression>
有没有一种方法可以使渲染包gzip成为内容?
最佳答案
如您所述,通过创建实现IBundleTransform的类来创建自定义包转换是正确的方法。例如,以下是使用SharpZipLib(via NuGet)进行GZip压缩的捆绑转换示例:
public class GZipTransform : IBundleTransform
{
string _contentType;
public GZipTransform(string contentType)
{
_contentType = contentType;
}
public void Process(BundleContext context, BundleResponse response)
{
var contentBytes = new UTF8Encoding().GetBytes(response.Content);
var outputStream = new MemoryStream();
var gzipOutputStream = new GZipOutputStream(outputStream);
gzipOutputStream.Write(contentBytes, 0, contentBytes.Length);
var outputBytes = outputStream.GetBuffer();
response.Content = Convert.ToBase64String(outputBytes);
// NOTE: this part is broken
context.HttpContext.Response.Headers["Content-Encoding"] = "gzip";
response.ContentType = _contentType ;
}
}
现在,这是不幸的部分-在测试此样本时,我发现了一个使它无法工作的错误。最初的设计期望人们会做一些非常简单的事情-因此,BundleResponse公开了允许您设置内容(更具体地说是字符串内容)和内容类型的属性。 BundleContext公开HttpContext的属性,这会使一个有理智的人相信可以在此处设置响应的其他属性(如上所示)。但是,这有两个方面的误导性:
我们正在认真研究下一版框架的设计,以使您能够指定HTTP响应消息的所有(理想情况)方面,而这些方面不包含HTTP上下文(这意味着很容易实现)。
另一注。要提供自定义的包转换,您需要回退到创建Bundle的实例,而不是创建ScriptBundle/StyleBundle。这些类实际上只是具有预配置包转换的包的简写类型。要基于捆绑创建捆绑,您需要执行以下操作:
var jqueryBundle = new Bundle("~/bundles/jqueryall", new GZipTransform("text/javascript"));
jqueryBundle.Include("~/Scripts/jquery-1.*",
"~/Scripts/jquery-ui*",
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*");
bundles.Add(jqueryBundle);
关于asp.net-mvc-3 - GZip system.web.optimization捆绑包,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11300839/