0
votes

I would like to implement caching at the action level in MVC in a certain way.

I am aware of the OutputCache attribute, but I can't cache the entire page.

I would like to cache the model returned by the action.

So basically, I want to create a filter that will prevent the action method from being invoked, but have MVC behave as if it was invoked.

Assume that I plan on ignoring any "return View("viewName")" assuming all will be "return View()".

2

2 Answers

1
votes

You can create a filter that inherits from ActionFilterAttribute

This is what I use

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();

    }
}
0
votes

You can do partial caching. For example, you can make an action method which IS NOT invoked as a regular action, but rather renders a partial view (an HTML snippet eventually) by calling Html.RenderPartial(). That way, you don't cache the whole page, but only those fragments which change less frequently.