覆盖 ASP.NET 缓存策略并将 Cache-Control 设置为 public

Pie*_*one 2 c# asp.net asp.net-mvc caching

我想在我的 ASP.NET (MVC) 应用程序中设置Cache-Control标头public。问题是有代码(我无法更改)之前设置了这样的缓存策略:

        var response = htmlHelper.ViewContext.HttpContext.Response;
        response.Cache.SetExpires(System.DateTime.UtcNow.AddDays(-1));
        response.Cache.SetValidUntilExpires(false);
        response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.Cache.SetNoStore();
Run Code Online (Sandbox Code Playgroud)

后面我找不到覆盖这个的方法,因为无论我如何尝试设置缓存控制,上面的都会生效。例如,以下任何一项都不能对抗先前禁用的缓存:

        httpContext.Response.Headers["Cache-Control"] = "public";
        var cache = httpContext.Response.Cache;
        cache.SetExpires(cacheItem.ValidUntilUtc);
        cache.SetValidUntilExpires(true);
        cache.SetRevalidation(HttpCacheRevalidation.None);
        cache.SetCacheability(HttpCacheability.Public);
        cache.SetMaxAge(cacheItem.ValidUntilUtc - _clock.UtcNow);
Run Code Online (Sandbox Code Playgroud)

有没有办法以某种方式覆盖或重置缓存策略?

Pie*_*one 6

显然这不是简单的可能,因为它HttpCachePolicy会主动阻止您设置“更高”的可缓存性,即如果您在设置 NoCache 后尝试设置 Public,则不会发生任何事情。

似乎唯一的hackish方法是使用私有反射并调用内部Reset方法,如下所示:

        var cache = httpContext.Response.Cache;
        var cachePolicy = (HttpCachePolicy)typeof(HttpCachePolicyWrapper).InvokeMember("_httpCachePolicy", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField, null, cache, null);
        typeof(HttpCachePolicy).InvokeMember("Reset", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, cachePolicy, null);
        cache.SetCacheability(HttpCacheability.Public);
Run Code Online (Sandbox Code Playgroud)