Conditional output caching in ASP.NET

I have a question on how to instruct ASP.NET programmatically to skip request resolution from the output cache.

Imagine that you got the page’s cache page (for example, http: //domain/page.aspx ) by applying the cache policy settings from CMS to HttpResponse at runtime. The query-based , depending on whether the current user is authenticated + member of a set of known groups (or corresponding business logic), I would like to instruct ASP.NET to skip request permission from the output cache.

The scenario is that two different users are on the system at the same time (or more). User A is authenticated + a member of a set of known groups, and user B is anonymous. No matter which page is displayed in the cache, I want the authenticated user to view all the pages, as if output caching were not enabled; at the same time, I would like ASP.NET to continue to serve output cached pages to anonymous users (or to users who do not comply with business logic).

A typical suggestion is to use VaryByHeader, VaryByParam, etc. and pollution of the output cache is not very good, but digging into the output cache module using Reflector, I noticed that the output cache module skips the current request if a pair of Known cache control headers are present. As for the headers, they are sent from the browser if the user forces a new copy to be displayed by pressing F5 or ENTER in the address bar.

So, I just set the "cache-control" header to "no-cache" in the custom http module in the event that happens before the ResolveRequestCache event, to which the output cache subscribes. Like this:

context.Request.Headers["Cache-Control"] = "no-cache";

dandy, , ​​ HttpCachePolicy.SetValidUntilExpires(true), ASP.NET .

, , http-, , HttpCachePolicy.SetValidUntilExpires(false) , , , , , ASP.NET . , .

, , HttpCachePolicy, :

HttpResponse.Cache.SetNoServerCaching()).
+5
2

HttpCacheValidateHandler , , . ResolveRequestCache, . HttpValidationStatus.IgnoreThisRequest , .

HttpModule :

public class CacheModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest +=
            (s, e) => context.Context.Response.Cache
                        .AddValidationCallback(CacheHandler, null);
    }

    private static void CacheHandler(
        HttpContext context, object data,
        ref HttpValidationStatus validationstatus)
    {
        // bypass cache for all users with skipCache cookie
        validationstatus =
            context.Request.Cookies["skipCache"] != null
                ? HttpValidationStatus.IgnoreThisRequest
                : HttpValidationStatus.Valid;
    }

    public void Dispose()
    {
    }
}
+3

, , - .

VaryByHeader? , , , , . , , , . .

0

All Articles