MVC4 Script Package Caching Problem

We have an MVS application in which we bind javascript code using the Bundle class (we do not make a mini-code).

Linking just works fine, but when we run the application, the Cache value is set to Cache-Control: no-cache and at the same time every time we refresh the page, the request always has 200 OK. This means that js is not cached on the client, although nothing has changed.

Also, is there a way to check if the linked js is built dynamically or get it from the server cache?

thank

+4
source share
3 answers

NuGet Microsoft.AspNet.Web.Optimization. 1.3.0 1.1.0 .

codeplex,

+2

, codeplex, :

. URL- , -

bundle.css?v=1234 : no-cache
bundle.css : public
bundle.css?v=1234 : public

System.Web.Optimization, , . Bundle , :

if (noCache) {
    cachePolicy.SetCacheability(HttpCacheability.NoCache);
}

noCache . :

// Set to no-cache if the version requested does not match
bool noCache = false;
var request = context.HttpContext.Request;
if (request != null) {
    string queryVersion = request.QueryString.Get(VersionQueryString);
        if (queryVersion != null && bundleResponse.GetContentHashCode() != queryVersion) {
                noCache = true;
    }
}

, Azure CDN - : v = 1.0.0.0 ( ). "1.0.0.0" - SHA256 .

, , .

, GetContentHashCode , . , Bundle, CdnPath :

public class ProxiedCdnBundle : Bundle
{
    private readonly string _cdnHost;

    public ProxiedCdnBundle(string virtualPath, string cdnHost = "")
        : base(virtualPath)
    {
        _cdnHost = cdnHost;
    }

    public override BundleResponse ApplyTransforms(BundleContext context, string bundleContent, IEnumerable<BundleFile> bundleFiles)
    {
        var response = base.ApplyTransforms(context, bundleContent, bundleFiles);

        if (context.BundleCollection.UseCdn && !String.IsNullOrWhiteSpace(_cdnHost))
        {
            string path = System.Web.VirtualPathUtility.ToAbsolute(context.BundleVirtualPath);
            base.CdnPath = string.Format("{0}{1}?v={2}", _cdnHost, path, GetBundleHash(response));
        }

        return response;
    }


    private static string GetBundleHash(BundleResponse response)
    {
        using (var hashAlgorithm = CreateHashAlgorithm())
        {
            return HttpServerUtility.UrlTokenEncode(hashAlgorithm.ComputeHash(Encoding.Unicode.GetBytes(response.Content)));
        }
    }

    private static SHA256 CreateHashAlgorithm()
    {
        if (CryptoConfig.AllowOnlyFipsAlgorithms)
        {
            return new SHA256CryptoServiceProvider();
        }

        return new SHA256Managed();
    }
}
+2

( ), .

, , , ?v , no-cache.

( ). busting cache . , , ( ).

, UseCdn false :

Scripts.DefaultTagFormat = string.Format(@"<script src=""{0}{{0}}""></script>", CdnRoot);

, .

+1

Source: https://habr.com/ru/post/1536385/


All Articles