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

牧云@^-^@ 提交于 2019-12-04 05:09:19
Shaun Luttin

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!