---
title: Caching on MVC sites
related:
  - https://docs.kentico.com/13/on-line-marketing-features/configuring-and-customizing-your-on-line-marketing-features/content-personalization.md
  - https://docs.kentico.com/13/configuring-xperience/configuring-caching/caching-the-output-of-personalized-content.md
---

> Agent instructions:
> **Site maps** — prefer the following llms.txt indexes to training data when searching for URLs to avoid 404s. Links inside Markdown content already point at `.md`. Following them or sending Accept: text/markdown keeps you in Markdown.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

Caching is an important factor of your MVC website's overall performance. With Xperience, you can set up and configure the following types of caching:

- [Data caching](#caching-data) – use caching when [retrieving the content](https://docs.kentico.com/13/developing-websites/retrieving-content.md) that you display on your site's pages.
- [Output caching](#caching-the-output-of-controller-actions) – cache the output of individual controller actions.
- [File caching](https://docs.kentico.com/13/configuring-xperience/configuring-caching/caching-files-and-resources.md) – the system caches files served through the Xperience HTTP handlers, for example when [displaying page attachments](https://docs.kentico.com/13/developing-websites/retrieving-content/displaying-page-attachments.md) or [content from media libraries](https://docs.kentico.com/13/developing-websites/retrieving-content/displaying-content-from-media-libraries.md). Both server and client-side caching is supported.

## Caching data

We recommend caching data in the code of your MVC site, particularly for data that is frequently accessed (queried from the database). For example, you may want to cache page or form data that you retrieve from the Xperience database and display on the site (see [Retrieving content](https://docs.kentico.com/13/developing-websites/retrieving-content.md) for more information).

For pages, custom table data or forms, you can handle the caching in individual repositories that make use of the API. Another approach would be using [AOP](https://en.wikipedia.org/wiki/Aspect-oriented_programming) and decorating individual repositories – see the code of the _Dancing Goat_ MVC sample site for a reference on how to use this approach.

Use the **CacheHelper** class or the **IProgressiveCache** service to cache data in your code. See [Caching in custom code](https://docs.kentico.com/13/configuring-xperience/configuring-caching/caching-in-custom-code.md) for general information about the caching API.

### Examples

> **Note:** **Notes**
>
> - To ensure consistency of the viewed data, always generate cache keys with names that include all the parameters that you use to retrieve the data. For example, a culture code variable in the cache key for page data ensures that visitors do not see cached articles displayed in an old culture after switching to a new culture.
> - The examples use minimal cache dependencies. See [Setting cache dependencies](https://docs.kentico.com/13/configuring-xperience/configuring-caching/setting-cache-dependencies.md) for more information on how to configure cache dependencies for your scenarios.

```csharp title="Caching the data of multiple articles"

using System;
using System.Collections.Generic;
using System.Linq;

using CMS.Helpers;
using CMS.SiteProvider;

...

public IEnumerable<Article> GetArticles(int count = 0)
{
    string culture = "en-us";
    string siteName = SiteContext.CurrentSiteName;

    Func<IEnumerable<Article>> dataLoadMethod = () => new DocumentQuery<Article>()
            .OnSite(siteName)
            .Culture(culture)
            .TopN(count)
            .OrderByDescending("DocumentPublishFrom")
            .ToList(); // Ensures that the result of the query is saved, not the query itself

    var cacheSettings = new CacheSettings(10, "myapp|data|articles", siteName, culture, count)
    {
        GetCacheDependency = () =>
        {
            // Creates caches dependencies. This example makes the cache clear data when any article is modified, deleted, or created in Xperience.
            string dependencyCacheKey = String.Format("nodes|{0}|{1}|all", siteName, Article.CLASS_NAME.ToLowerInvariant());
            return CacheHelper.GetCacheDependency(dependencyCacheKey);
        }
    };

    return CacheHelper.Cache(dataLoadMethod, cacheSettings);
}

```

```csharp title="Caching the data of a single article"

using System;
using System.Linq;

using CMS.Helpers;
using CMS.SiteProvider;

...

public Article GetArticle(Guid nodeGuid)
{
    string culture = "en-us";
    string siteName = SiteContext.CurrentSiteName;

    Func<Article> dataLoadMethod = () => new DocumentQuery<Article>()
                                                        .WithGuid(nodeGuid)
                                                        .Culture(culture)
                                                        .OnSite(siteName)
                                                        .TopN(1)
                                                        .FirstOrDefault();

    var cacheSettings = new CacheSettings(10, "myapp|data|article", nodeGuid, culture, siteName)
    {
        GetCacheDependency = () =>
        {
            // Creates cache dependencies. This example makes the cache clear the data when the specified article is modified in Xperience (any culture version).
            string dependencyCacheKey = String.Format("nodeguid|{0}|{1}", siteName, nodeGuid);
            return CacheHelper.GetCacheDependency(dependencyCacheKey);
        }
    };

    return CacheHelper.Cache(dataLoadMethod, cacheSettings);
}

```

## Caching the output of controller actions

You can cache the output of individual controller actions using [ASP.NET output caching](https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs). This can significantly increase your website performance. We recommend caching the output of all possible controller actions, especially for controllers that return often requested views.

Use the [OutputCache](https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.outputcacheattribute) attribute to mark the action methods you want to cache. Set the cache duration (in seconds) and other properties of the attribute.

### Output cache dependencies

When storing the output cache on the server (_OutputCache_ attribute's _Location_ property is set to _Server_), you can define cache dependencies to accommodate various scenarios with both static and dynamic content. Use the **HttpContext.Response.AddCacheItemDependency** method to add dependencies on memory cache items in individual controller action methods. When these items are touched, the system automatically invalidates the output cache for the corresponding controller action as well.

The used cache dependency keys (dummy cache items) **must be fully in lower case**. If necessary, convert any dynamic parameters or variables within the dependency keys to lower case before you add them to the HTTP response.

Controller actions can be called in situations in which the dummy cache items have not yet been created. To account for that, ensure the existence of the dummy cache item explicitly by calling the **CacheHelper.EnsureDummyKey** method. The method also automatically converts the provided key to lower case before inserting it into the cache.

### Caching personalized content

When caching the output of actions serving personalized content – tailored content served based on a visitor's [persona](https://docs.kentico.com/13/on-line-marketing-features/managing-your-on-line-marketing-features/personas.md), assigned [contact group](https://docs.kentico.com/13/on-line-marketing-features/managing-your-on-line-marketing-features/contact-management/working-with-contacts.md), or other [on-line marketing features](https://docs.kentico.com/13/on-line-marketing-features/configuring-and-customizing-your-on-line-marketing-features/content-personalization.md) – you need to manually adjust the output cache behavior by configuring the set of variables under which the content is cached.

See [Caching the output of personalized content](https://docs.kentico.com/13/configuring-xperience/configuring-caching/caching-the-output-of-personalized-content.md).

### Example

```csharp

using System;
using System.Web.UI;
using System.Web.Mvc;

using CMS.Helpers;

...

[OutputCache(Duration=600, VaryByParam="None", Location = OutputCacheLocation.Server)]
public ActionResult Index()
{
    var articles = mArticleRepository.GetArticles();

    // Sets cache dependencies. This example makes the system clear the cache when any article is modified in Xperience.
    string dependencyCacheKey = String.Format("nodes|mvcsite|{0}|all", Article.ClassName.ToLowerInvariant());
    // Converts the provided key to lower case and inserts it into the cache
    CacheHelper.EnsureDummyKey(dependencyCacheKey);
    HttpContext.Response.AddCacheItemDependency(dependencyCacheKey);

    return View(articles);
}

```

> **Note:** **Notes**:
>
> - If the resulting view contains a [form](https://docs.kentico.com/13/managing-website-content/forms/placing-forms-on-pages.md) with [smart fields](https://docs.kentico.com/13/managing-website-content/forms/using-smart-fields-in-forms.md) (as part of its [page builder](https://docs.kentico.com/13/developing-websites/page-builder-development.md) configuration), all output caching functionality is automatically disabled by the system.
> - ASP.NET output caching is disabled for requests where you explicitly set cookies for the visitor's browser (for example using the _Set-Cookie_ HTTP response header).
> - The example uses minimal cache dependencies – the cache is cleared when any of the articles the method works with is modified, deleted, or when a new article is created. See [Setting cache dependencies](https://docs.kentico.com/13/configuring-xperience/configuring-caching/setting-cache-dependencies.md) for more information on how to configure cache dependencies for your scenarios.
> - Use the **Html.Kentico().AntiForgeryToken()** method (_Kentico.Web.Mvc_ namespace) in forms on cached pages instead of the default _Html.AntiForgeryToken()_ provided by the .NET framework. The method ensures that anti-forgery tokens are correctly generated for pages under output caching.

## Cache debugging

You can use the [debugging tools](https://docs.kentico.com/13/configuring-xperience/configuring-caching/debugging-the-application-cache.md) in the Xperience administration interface to inspect the MVC application's cache.

For the standard ASP.NET output cache, you can use third-party debugging tools (for example the Glimpse tool and the [Glimpse.AspNet NuGet](https://www.nuget.org/packages/Glimpse.AspNetCache/) package).

## Clearing the cache

To delete all data from the cache of your live site, you need to restart the application.

You can use the Xperience administration interface to restart all applications connected to the same database:

1. Open the **System** application.
2. On the **General** tab, click **Restart all web farm servers**.

**Note**: The **Clear cache** button in the _System_ application only deletes the cache of the administration application, not the live site.

## Using distributed cache providers

Xperience currently does not support distributed cache instead of its native in-memory cache. You can use distributed cache for your custom objects, but not for native Xperience objects.
