8

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?

Martin Kearn
  • 2,313
  • 1
  • 21
  • 35

3 Answers3

14

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

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

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.

Andreas
  • 1,355
  • 9
  • 15
1

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

  • Hi Thanks for this. Can you give some insight on how I'd wire-up this middleware in startup.cs (middleware is a new concept for me) – Martin Kearn Sep 02 '15 at 08:59