你可以预先缓存ASP.NET Bundles吗?

时间:2013-07-15 20:12:39

标签: c# asp.net asp.net-optimization system.web.optimization

每次部署MVC Web应用程序时,我的服务器都必须重新缓存所有js和css包。

因此,部署后第一个视图渲染可能需要几秒钟。

有没有办法预先缓存捆绑包?毕竟,文件在编译时是静态的。

1 个答案:

答案 0 :(得分:11)

解决方案

为了解决这个问题,我们将默认内存缓存替换为持续超出App Pool生命周期的缓存。

为此,我们继承了ScriptBundle并覆盖了CacheLookup()UpdateCache()

/// <summary>
/// override cache functionality in ScriptBundle to use 
/// persistent cache instead of HttpContext.Current.Cache
/// </summary>
public class ScriptBundleUsingPersistentCaching : ScriptBundle
{
    public ScriptBundleUsingPersistentCaching(string virtualPath)
        : base(virtualPath)
    { }

    public ScriptBundleUsingPersistentCaching(string virtualPath, string cdnPath)
        : base(virtualPath, cdnPath)
    { }

    public override BundleResponse CacheLookup(BundleContext context)
    {
        //custom cache read
    }

    public override void UpdateCache(BundleContext context, BundleResponse response)
    {
        //custom cache save
    }
}

并发症

唯一值得注意的其他扳手与我们的持久缓存工具有关。为了缓存,我们必须有一个可序列化的对象。很遗憾,BundleResponse未标记为Serializable

我们的解决方案是创建一个小实用程序类,将BundleResponse解构为其值类型。一旦我们这样做,我们就能够序列化实用程序类。然后,当从缓存中检索时,我们重建BundleResponse

相关问题