How to enable ClientCache in ASP.NET Core

5.4k Views Asked by At

In ASP.net 4.5 we used to be able to enable expires headers on static resources (in-turn, enabling browser caching) by adding 'ClientCache' to the web.config, something like:

<staticcontent>
  <clientcache cachecontrolmode="UseMaxAge" cachecontrolmaxage="365.00:00:00" />
</staticcontent>

As referenced in http://madskristensen.net/post/cache-busting-in-aspnet

How do we do this now in ASP.net 5 when we have no web.config and Startup.cs?

3

There are 3 best solutions below

0
On BEST ANSWER

In Startup.cs > Configure(IApplicationBuilder applicationBuilder, .....)

applicationBuilder.UseStaticFiles(new StaticFileOptions
{
     OnPrepareResponse = context => 
     context.Context.Response.Headers.Add("Cache-Control", "public, max-age=2592000")
});
3
On

If you are using MVC you can use the ResponseCacheAttribute on your actions to set client cache headers. There is also a ResponseCacheFilter you can use.

1
On

What server do you use?

  • If you use IIS you can still use web.config in your wwwroot folder.

  • If you use kestrel there is no in-built solution yet. However you can write a middleware that adds the specific cache-control header. Or use nginx as a reverse proxy.

Middleware:

NOT tested (!) and just on top of my head you can write something like this:

public sealed class CacheControlMiddleWare
{
    readonly RequestDelegate _next;
    public CacheControlMiddleWare(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Path.Value.EndsWith(".jpg")
        {
            context.Response.Headers.Add("Cache-Control", new[]{"max-age=100"});
        }
        await _next(context);
    }
}

nginx as a reverse proxy:

http://mjomaa.com/computer-science/frameworks/asp-net-mvc/141-how-to-combine-nginx-kestrel-for-production-part-i-installation

Beside that, I've wrote some notes for response caching:

http://mjomaa.com/computer-science/frameworks/asp-net-mvc/153-output-response-caching-in-asp-net-5