I am using ASP.NET WebApi and have the following code to stop caching in everything:
public override System.Threading.Tasks.Task<HttpResponseMessage> ExecuteAsync(System.Web.Http.Controllers.HttpControllerContext controllerContext, System.Threading.CancellationToken cancellationToken)
{
System.Threading.Tasks.Task<HttpResponseMessage> task = base.ExecuteAsync(controllerContext, cancellationToken);
task.GetAwaiter().OnCompleted(() =>
{
task.Result.Headers.CacheControl = new CacheControlHeaderValue()
{
NoCache = true,
NoStore = true,
MaxAge = new TimeSpan(0),
MustRevalidate = true
};
task.Result.Headers.Pragma.Add(new NameValueHeaderValue("no-cache"));
task.Result.Content.Headers.Expires = DateTimeOffset.MinValue;
});
return task;
}
The result headers look like this (chrome):
Cache-Control:no-store, must-revalidate, no-cache, max-age=0
Content-Length:1891
Content-Type:application/json; charset=utf-8
Date:Fri, 19 Jul 2013 20:40:23 GMT
Expires:Mon, 01 Jan 0001 00:00:00 GMT
Pragma:no-cache
Server:Microsoft-IIS/8.0
I added the "no-store" after reading about the bug (How to stop chrome from caching).
However, no matter what I do, when I do something that navigates me away from this page, and then use the "back" button, chrome always loads from cache:
Request Method:GET
Status Code:200 OK (from cache)
Does anyone have any idea why this is happening? I have confirmed that the server is never hit for this request.
When you're in Google Chrome, click on View, then select Developer, then Developer Tools. Alternatively, you can right click on a page in Chrome, then click Inspect. Click on the Network tab, then check the box to Disable cache.
Just use the Cache-Control: no-cache header. Implement it as delegating-Handler and make sure your header is applied (with MS Owin Implementation hook up on OnSendingHeaders() .
Caching in REST APIs POST requests are not cacheable by default but can be made cacheable if either an Expires header or a Cache-Control header with a directive, to explicitly allows caching, is added to the response. Responses to PUT and DELETE requests are not cacheable at all.
The answer is that Chrome does not like "Expires:Mon, 01 Jan 0001 00:00:00 GMT" (a fake date, basically).
I changed my date to be what they use in their Google API, and it worked:
Cache-Control:no-store, must-revalidate, no-cache, max-age=0
Content-Length:1897
Content-Type:application/json; charset=utf-8
Date:Fri, 19 Jul 2013 20:51:49 GMT
Expires:Mon, 01 Jan 1990 00:00:00 GMT
Pragma:no-cache
Server:Microsoft-IIS/8.0
So, for anyone else who comes across this problem, make sure you set your Expires date to this arbitrary date!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With