Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output caching in HTTP Handler and SetValidUntilExpires

I'm using output caching in my custom HTTP handler in the following way:

    public void ProcessRequest(HttpContext context)
    {
        TimeSpan freshness = new TimeSpan(0, 0, 0, 60);
        context.Response.Cache.SetExpires(DateTime.Now.Add(freshness));
        context.Response.Cache.SetMaxAge(freshness);
        context.Response.Cache.SetCacheability(HttpCacheability.Public);
        context.Response.Cache.SetValidUntilExpires(true);
        ...
    }

It works, but the problem is that refreshing the page with F5 leads to page regeneration (instead of cache usage) despite of the last codeline:

context.Response.Cache.SetValidUntilExpires(true);

Any suggestions?

UPD: Seems like the cause of problem is that HTTP handler response isn't caching on server. The following code works well for web-form, but not for handler:

        Response.Cache.SetCacheability(HttpCacheability.Server);

Are there some specifics of the caching the http handler response on server?

like image 957
mayor Avatar asked Jun 08 '10 20:06

mayor


1 Answers

I've found the reason. Query string parameter is using in my URL, so it looks like "http://localhost/Image.ashx?id=49". I've thought that if VaryByParams is not set explicitly, server will always take value of id param into account, because context.Response.Cache.VaryByParams.IgnoreParams is false by default. But in fact, server doesn't use cache at all in this case (nevertheless user browser does).

So, if parameters are using in query string, Response.Cache.VaryByParams should be set explicitly, like

context.Response.Cache.VaryByParams.IgnoreParams = true;

for ignoring parameters or

context.Response.Cache.VaryByParams[<parameter name>] = true;

for variation by some parameter or

context.Response.Cache.VaryByParams["*"] = true;

for variation by all parameters.

like image 69
mayor Avatar answered Nov 22 '22 11:11

mayor