In my previous post Cache tag helper in MVC 6 i explained how you can cache certain parts from you view. In this post I’ll show you how you can cache the entire output of a controller action and how you can define cache profiles that can be used in your entire application.

Reponse cache

To apply caching in a controller, you just need to apply the ResponseCaching attribute at the controller class. If you just want to cache a specific action on a controller you can also apply this attribute on a action method of the controller. The attribute on the controller will always be overridden by the attribute placed on a action method.

This attribute has some properties that can be used to modify the caching behaviour. In this example all the output of the HomeController will be cached for 60 seconds, expect for the Contact method which will be cached for 30 seconds.

   [ResponseCache(Duration=30)]
    public class HomeController : Controller
    {       
        public IActionResult Index()
        {
            return View();
        }

        [ResponseCache(Duration=60)]
        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }
}

Cache Profiles

Configuring the cache in the attribute directly works fine in small applications, but i doesn’t give you the possibility to define a global caching strategy.  If you change something in your caching strategy, you would need to look at every attribute to change it’s configuration. With cache profiles you can evict this problem.

You define these profiles in the startup class.

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc(options =>
    {
        options.CacheProfiles.Add("default", 
            new CacheProfile()
            {
                Duration=60
            });
        options.CacheProfiles.Add("short",
            new CacheProfile()
            {
                Duration = 30
            });
    });
}

The ResponseCache attribute also has a property “CacheProfileName”. These property will make the mapping between the attribute and the defined cache profiles.

    [ResponseCache(CacheProfileName="default")]
    public class HomeController : Controller
    {       
        public IActionResult Index()
        {
            return View();
        }

        [ResponseCache(CacheProfileName="short")]
        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }
    }

Because everything is centralized now, you can easily change your caching strategy and try out different configurations.

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>