Configure the MVC.NET OutputCache to return 304 Not Modified if an ActionResult hasn't changed

前端 未结 1 1089
花落未央
花落未央 2021-02-15 19:46

Introduce the Problem

We have successfully configured the browser cache to return a saved response if the server indicates 304 Not Modified.

1条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-15 19:58

    The following is working for us.

    Web.Config

    Set Cache-Control:private,max-age-0 to enable caching and force re-validation.

    
      
        
          
            
          
        
      
    
    

    Action

    Respond with 304 if the response is not modified.

    [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");
        }
    }
    

    Filter

    Remove the Cache-Control:private,max-age-0 otherwise the cache will store the status message.

    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

    Fiddler shows that the cache is acting appropriately.

    Successful Fiddler

    0 讨论(0)
提交回复
热议问题