How to stop chrome from caching REST response from

2019-03-18 17:04发布

问题:

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.

回答1:

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!