How do I set a Cache-Control on static assets? (dotnet 5+)

  • Page Owner: Not Set
  • Last Reviewed: 2023-01-24

How do I set a cache-control on static assets? Specifically dotnet 5+ and Optimizely 12+


Answer

You can do something like this for all static assets:

var cacheMaxAgeOneWeek = (60 * 60 * 24 * 7).ToString();
app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        ctx.Context.Response.Headers.Append(
             "Cache-Control", $"public, max-age={cacheMaxAgeOneWeek}");
    }
});

Or you can set it for a specific file type something like this:

public class PdfStaticFilePreProcessor: IStaticFilePreProcessor
    {
        public int Order => 10;

        public void PrepareResponse(StaticFileResponseContext staticFileResponseContext)
        {
            if(staticFileResponseContext.Context.Response.ContentType == "application/pdf")
            {
                if (staticFileResponseContext.Context.Response.Headers.ContainsKey("Cache-Control"))
                {
                    staticFileResponseContext.Context.Response.Headers["Cache-Control"] = "no-cache";
                }
                else
                {
                    staticFileResponseContext.Context.Response.Headers.Add("Cache-Control", "no-cache");
                }
            }
        }
    }

There's probably a better way to do it but that's they way I got working.