ASP.NET Core Response Cache
Does ASP.NET Core have an output cache? If so, where can you find it and how can you use it? In this tutorial, you'll learn just that!
Join the DZone community and get the full member experience.
Join For Freewhere is the output cache in asp.net core? is it gone? no, it’s there but in new and better extensible form, and it is called now response caching. this blog post shows how to use response caching on asp.net core and provides tips about some of the internals of it.
in asp.net core caching is solved as a middleware service that comes with microsoft.aspnetcore.responsecaching nuget package . in mvc, caching is driven by the responsecache attribute. it’s possible to use the responsecache attribute without also response caching the middleware to just set response headers. this way, it is possible to tell the browser to cache content, and also cache or proxy servers on the way that can read these headers to find out how to cache page.
by default, response caching uses memory based cache, but there are extension points that allow you to use custom cache storage providers. this blog post doesn’t cover extensibility. it just covers the basics and focuses on stateless public sites.
using response caching
after adding package reference to microsoft.aspnetcore.responsecaching we can register response caching middleware in startup class using addresponsecaching() and useresponsecaching() extension methods.
public void configureservices(iservicecollection services)
{
// ...
services.addresponsecaching();
services.addmvc();
// ...
}
public void configure(iapplicationbuilder app, ihostingenvironment env, iloggerfactory loggerfactory)
{
// ...
app.useresponsecaching();
app.usemvc(routes =>
{
routes.maproute(
name: "default",
template: "{controller=home}/{action=index}/{id?}",
defaults: ""
);
});
}
for mvc controller action we add responsecache attribute. the following example shows primitive controller action that returns just a simple view it has.
[responsecache(duration = 30)]
public iactionresult article()
{
return view();
}
this is enough to get caching to work with minimal effort. when we run our application and request controller action that is cached we get the following result:
for a full list of the cache settings that are available check out the following pages from official documentation:
- response caching (asp.net core documentation)
- response caching middleware (asp.net core documentation)
caching profiles can be defined in application startup class and they are supported by responsecache attribute.
conditions for caching
the response caching middleware page by microsoft lists conditions that a request must meet for caching:
- the request must result in a 200 (ok) response from the server.
- the request method must be get or head.
- terminal middleware, such as static file middleware, must not process the response prior to the response caching middleware.
- the authorization header must not be present.
- cache-control header parameters must be valid, and the response must be marked public and not marked private.
- the pragma: no-cache header/value must not be present if the cache-control header is not present, as the cache-control header overrides the pragma header when present.
- the set-cookie header must not be present.
- vary header parameters must be valid and not equal to *.
- the content-length header value (if set) must match the size of the response body.
- the httpsendfilefeature is not used.
- the response must not be stale as specified by the expires header and the max-age and s-maxage cache directives.
- response buffering is successful, and the total length of the response is smaller than the configured limit.
- the response must be cacheable according to the rfc 7234 specifications. for example, the no-store directive must not exist in request or response header fields. see 'section 3: storing responses in caches of the rfc document' for details.
problems with cookies
currently, it is not possible to use cookies with response caching. as soon as the cookies header is present the caching of the request is considered impossible. services like application insights and antiforgery system by asp.net core don’t work with response caching because they use cookies or set cache headers.
for application insights and services like this, it is technically possible to create custom middleware based on default one if cookies are still needed for client-side libraries and there are no dependencies with the application or session state.
troubleshooting caching
to some degree, it is possible to monitor response caching. the library uses the asp.net core logging framework to log some activities by response caching middleware. the screen fragment below shows some response caching middleware logs.
sadly, it does not report reasons why the response was not added to the cache. it would help greatly to test our response caching in different environments.
if logs are not enough, then we can always include projects from the response caching github repository to our solution and run these on the debugger to see what’s going on.
when debugging response caching with the browser make sure that the developers' tools that come with the browser don’t set any cookies or cache headers that may affect response caching.
getting rid of arr affinity cookie on azure web sites
if your site doesn’t need application request routing (arr) you can disable the arr affinity cookie by adding the following block of settings to the web.config of your web application.
<system.webserver>
<httpprotocol>
<customheaders>
<add name="arr-disable-session-affinity" value="true"/>
</customheaders>
</httpprotocol>
</system.webserver>
after this modification, there is no more arr cookies available in your site.
wrapping up
although i got response caching to work, i didn’t get it work with application insights and other services that work in a browser and that use cookies. still, i was able to create a simple prototype of a public facing application that is cookieless and uses asp.net core response caching. in this example, i used a memory based cache as i wrote my proof-of-concept code. it was easy to set responsecache attributes to controller actions that i wanted to cache. troubleshooting was a little bit tricky because response cache logs are limited and browser tools may get in the way with their handling of cache headers. as a conclusion, i can say that response caching works okay but needs some improvements to be easier to use.
Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments