Output Caching in ASP.NET Core and MVC 6

 

        Introduction:

 

                 Yesterday, Visual Studio 2015 CTP 6 has been released which include tooling and new templates for ASP.NET Core beta 3. You can find updates and improvments about ASP.NET Core in this release at here. In ASP.NET Core beta 3, the support for output caching has been added. In this article, I will show you how to use output cache in ASP.NET 5.

 

        Description:

 

                    Assuming that you are running Visual Studio 2015 CTP 6 (you can also get that from Azure VM) or later and you have created an ASP.NET Core web application. You can add ResponseCacheAttribute(an action filter) on your action or class to make your action method response cacheable. For example,

 

        [ResponseCache(Duration = 100)]
        public IActionResult Index()
        {
            return Content(DateTime.Now.ToString());
        }

 

                    The above ResponseCacheAttribute will make the response cache on client-side for 100 seconds. In other words, it will add Cache-Control header with max-age=100. If you are unaware about http caching then check this tutorial.  ResponseCacheAttribute includes Duration (gets or sets the duration in seconds for which the response is cached), NoStore (if true, will set Cache-Control: no-store), VaryByHeader (which set the http Vary header) and Location (which sets Cache-control header to public, private or no-cache). ResponseCache attribute also include CacheProfileName property(this property is not available in current beta 3 but in latest commits so you cannot use it with beta 3) which allows you to set Duration, NoStore, Location and VaryByHeader outside your controller so that you can re-use the same profile instead of repeating.. Here is an example,

 

        [ResponseCache(CacheProfileName = "MyProfile")]
        public IActionResult Index()
        {
            return Content(DateTime.Now.ToString());
        }
        ...............................................
        ...............................................
        public void ConfigureServices(IServiceCollection services)
        {
           //................................................
            services.Configurelt;MvcOptions>(options =>
            {
                options.CacheProfiles.Add("MyProfile", 
                    new CacheProfile
                    {
                        Duration = 100
                    });
            });

 

 

                   

        Summary:

                    ASP.NET Core beta 3 added the support for output cache which allows you to quickly add http caching in your aplication. In this article, I showed you how to add output caching in ASP.NET Core.

1 Comment

  • Excellent tutorial for adding output caching in applications!
    I must say with each release Visual Studio is getting better and better.
    Thanks Imran :)

Comments have been disabled for this content.