Question

I am developing my application in ASP.NET 4.5. I setup a webservice. The webservice get accessed by Jquery using a GET Ajax call. The function has a 'id' parameter and for each id it returns different content.

I want to cache that data both on server and client. On client I already know how to use 'CacheDuration' but the problem is with the client side. I use HttpFox to get the headers of each response.

I've setup the following code at the beginning of the function:

    HttpCachePolicy cache = HttpContext.Current.Response.Cache;
    cache.SetCacheability(HttpCacheability.Private);
    cache.SetExpires(DateTime.Now.AddMinutes((double)10));
    cache.SetMaxAge(new TimeSpan(0, 0, 10));


    FieldInfo maxAgeField = cache.GetType().GetField(
    "_maxAge", BindingFlags.Instance | BindingFlags.NonPublic);
    maxAgeField.SetValue(cache, new TimeSpan(0, 10, 0));

What I want to do is to prevent the client from sending a request again for the same ID, and do that for let's say.. 10 minutes. So at the first call the request will be made and we get response 200. At the second time the response header should be 304.

Right now the code above doesn't do that and I want to know how to achieve that. Again, I am talking on client-side caching that return 304, so it want go to the server again for the same 'id' until the cache is expired.

I know that it can be done using the code, so please don't submit IIS type of solutions.

Need your help to solve this.

Was it helpful?

Solution

You will need to implement the last modified header

Response.Cache.SetLastModified(lastWriteTime.Value.ToUniversalTime());

This will allow your client to check for last modified values and not refetch.

You could in theory fake the last modified time to the nearest 10 mins by using

public static DateTime Round10(this DateTime value)
{   
    var ticksIn10Mins = TimeSpan.FromMinutes(10).Ticks;

    DateTime dtReturn = (value.Ticks % ticksIn10Mins == 0) ? value : new DateTime((value.Ticks / ticksIn15Mins + 1) * ticksIn10Mins);
    if(dtReturn > DateTime.Now())
    {
        return dtReturn.AddMinutes(-10); 
    } else {
        return dtReturn;
    }
}


Response.Cache.SetLastModified(Round10(DateTime.Now);

This code is untested though

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top