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

前端 未结 1 1047
一向
一向 2021-02-15 19:41

Introduce the Problem

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

相关标签:
1条回答
  • 2021-02-15 19:51

    The following is working for us.

    Web.Config

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

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

    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)
提交回复
热议问题