← Back to articles

ASP.NET Core response cache

Part of my ASP.NET Core recipe series: enabling response caching so identical requests are served without re-executing the pipeline.

Tedd

ASP.NET Core comes with built-in support for response caching. Unlike cache-control header that tells client/proxies how long to cache data, the response cache will cache output of an action.

The advantage of caching is that you can decrease the amount of expensive operations on the server by caching the result.

Install

Install-Package Microsoft.AspNetCore.ResponseCaching

Use

The simplest form of this caching is to decorate an action with the ResponseCache attribute. Duration says how many seconds to cache the output.

[HttpGet]
[ResponseCache(Duration = 10)]
public string CurrentTime()
{
 return DateTime.Now.ToString();
} 

Note that the output may vary depending on HTTP headers, query variables, or post data. If this is the case then you need to specify so. For example:

[HttpGet]
[ResponseCache(Duration = 10, VaryByQueryKeys = new string[] { "SessionId" }, VaryByHeader = "User-Agent")]
public string CurrentDate(string sessionId)
{
 return DateTime.Now.ToString();
} 

Response caching supports much more complex scenarios.

Written by Tedd · Oslo, Norway

Follow the journal via RSS