2013-07-19 65 views
12

我使用ASP.NET的WebAPI,並有下面的代碼在一切停止緩存:如何停止Chrome緩存來自WebApi的REST響應?

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; 
} 

結果標題是這樣的(鉻):

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 

我添加了「NO-存儲「後閱讀有關錯誤(How to stop chrome from caching)。

Request Method:GET 
Status Code:200 OK (from cache) 

沒有人有任何:

但是,無論我做什麼,當我做一些導航我離開這個頁面,然後使用「返回」按鈕,鍍鉻總是從緩存加載想法爲什麼發生這種情況?我已經確認服務器從未被這個請求命中。

回答

7

答案是Chrome不喜歡「過期:星期一,01 Jan 0001 00:00:00 GMT」(基本上是假日期)。

我改變了我的日期是他們在谷歌API使用什麼,和它的工作:

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 

所以,對於其他人誰過這樣的問題來了,請確保您設置的過期日期這個任意日期!

+0

如果您設置了無存儲,則不要設置no-cache,must-revalidate,max-age和過期,因爲它們與無存儲相沖突。無存儲意味着該表示不能被存儲,並且其餘的說明解釋用於管理存儲的表示的規則。 –

+0

以及我剛剛添加無商店,因爲鉻錯誤,忽略無緩存和過期(見http://stackoverflow.com/questions/4146813/how-to-stop-chrome-from-caching)...所以,我不知道你想讓我做什麼。 – automaton

+0

不幸的是,不緩存並不意味着不緩存。這也不意味着Chrome無法使用緩存副本。這意味着在使用緩存副本之前,它必須先檢查服務器。如果服務器沒有返回正確的信息,chrome會高興地返回緩存的結果。 –