Output caching in HTTP Handler and SetValidUntilExpires
Asked Answered
A

2

7

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?

Action answered 8/6, 2010 at 20:27 Comment(0)
A
18

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.

Action answered 9/6, 2010 at 10:42 Comment(1)
Thanks for finding this solution, worked for me with single-valued query parameters. But when I have a multi-valued parameter like ?id=1&id=2&id=3 then this still does not work. I don't know why yet, but wanted to let others know about it.Telestich
H
0

public cacheability depends on user browser or proxy it specifies that the response is cacheable by clients and shared (proxy) caches.

had you tried using HttpCacheability.Server

http://msdn.microsoft.com/en-us/library/system.web.httpcacheability(v=VS.71).aspx

Hemotherapy answered 8/6, 2010 at 20:58 Comment(1)
I've tried it, but in this case caching doesn't work at all. I use ASP.NET development server.Action

© 2022 - 2024 — McMap. All rights reserved.