【问题标题】:Custom MVC3 caching filter attribute自定义 MVC3 缓存过滤器属性
【发布时间】:2013-03-29 19:05:27
【问题描述】:
我想以某种方式在MVC中实现动作级别的缓存。
我知道 OutputCache 属性,但我无法缓存整个页面。
我想缓存操作返回的模型。
所以基本上,我想创建一个过滤器来阻止调用操作方法,但让 MVC 的行为就像它被调用一样。
假设我打算忽略任何“return View("viewName")”,假设所有都是“return View()”。
【问题讨论】:
标签:
asp.net-mvc
asp.net-mvc-3
caching
【解决方案1】:
您可以创建一个继承自 ActionFilterAttribute 的过滤器
这是我用的
public class CacheControlAttribute : ActionFilterAttribute
{
public CacheControlAttribute(HttpCacheability cacheability)
{
_cacheability = cacheability;
}
private readonly HttpCacheability _cacheability;
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
cache.SetCacheability(_cacheability);
cache.SetExpires(DateTime.Now);
cache.SetAllowResponseInBrowserHistory(false);
cache.SetNoServerCaching();
cache.SetNoStore();
}
}
【解决方案2】:
您可以进行部分缓存。
例如,您可以创建一个不作为常规操作调用的操作方法,而是通过调用 Html.RenderPartial() 呈现部分视图(最终是 HTML sn-p)。这样一来,您就不会缓存整个页面,而只会缓存那些更改频率较低的片段。