2014-05-21 24 views
5

引進問題配置MVC.NET的OutputCache返回304未修改如果一個ActionResult沒有改變

我們已經成功地配置瀏覽器的緩存,如果服務器指示304 Not Modified返回保存的響應。下面是配置:

<caching> 
    <outputCacheSettings> 
    <outputCacheProfiles> 
     <add 
     name="TransparentClient" 
     location="Client" 
     duration="0" /> 
    </outputCacheProfiles> 
    </outputCacheSettings> 
</caching> 

的Web.config是完美的,並設置Cache-control:private, max-age=0使:

  1. 瀏覽器會緩存響應,
  2. 總是驗證緩存,
  3. 如果服務器響應304,則
  4. 將返回緩存的響應。

的問題是,我們的MVC.NET操作總是回覆200和304從未

的問題

我們如何配置輸出緩存返回一個304當一個ActionResult沒有改變不修改?

  • 在MVC.NET中是否有內置的緩存驗證?
  • 如果不是,我們如何推出我們自己的緩存驗證機制?

roll-our-own可能需要帶有ETag或Last-Modified的Action Filter。

屏幕快照

下面是一個屏幕截圖的Fiddler表示缺乏的304

  • 318是SHIFT +刷新。

  • 332是一個刷新,我們預計會導致304.問題。

Fiddler Web Debugger

搜索和研究

ASP.NET MVC : how do I return 304 "Not Modified" status?提到從操作中返回一個304。這並沒有提供一種方法使OutputCache準確地響應一個304.

Working with the Output Cache and other Action Filters顯示如何重寫OnResultExecuted,這將允許添加/刪除標題。

+1

你可能意思是#332 ... – haim770

回答

4

以下是爲我們工作。

的Web.Config

套裝Cache-Control:private,max-age-0啓用緩存和力再驗證。

<system.web> 
    <caching> 
    <outputCacheSettings> 
     <outputCacheProfiles> 
     <add name="TransparentClient" duration="0" location="Client" /> 
     </outputCacheProfiles> 
    </outputCacheSettings> 
    </caching> 
</system.web> 

行動

進行響應304,如果響應沒有被修改。

[MyOutputCache(CacheProfile="TransparentClient")] 
public ActionResult ValidateMe() 
{ 
    // check whether the response is modified 
    // replace this with some ETag or Last-Modified comparison 
    bool isModified = DateTime.Now.Second < 30; 

    if (isModified) 
    { 
     return View(); 
    } 
    else 
    { 
     return new HttpStatusCodeResult(304, "Not Modified"); 
    } 
} 

過濾

取出Cache-Control:private,max-age-0否則緩存將存儲的狀態信息。

public class MyOutputCache : OutputCacheAttribute 
{ 
    public override void OnResultExecuted(ResultExecutedContext filterContext) 
    { 
     base.OnResultExecuted(filterContext); 
     if (filterContext.HttpContext.Response.StatusCode == 304) 
     { 
      // do not cache the 304 response     
      filterContext.HttpContext.Response.CacheControl = "";     
     } 
    } 
} 

Fidder酒店

提琴手錶明緩存適當行動。

Successful Fiddler

相關問題