Wednesday, June 23, 2021

Adding Cache-Control headers to Static Files in ASP.NET Core

 Implement Caching to Static files in the asp.net core

When you create a new ASP.NET Core project from the default template, you will find the StaticFileMiddleware is added early in the middleware pipeline, with a call to AddStaticFiles() in Startup.Configure():

Please replace the app.UseStaticFiles() from the below code:

public void Configure(IApplicationBuilder app)
{
    // logging and exception handler removed for clarity

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

to

using Microsoft.Net.Http.Headers;

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =>
    {
        const int durationInSeconds = 60 * 60 * 24 * 14;
        ctx.Context.Response.Headers[HeaderNames.CacheControl] =
            "public,max-age=" + durationInSeconds;
    }
});


This enables serving files from the wwwroot folder in your application. The default template contains a number of static files (site.cssbootstrap.cssbanner1.svg) which are all served by the middleware when running in development mode. It is these we wish to cache.

for more details - https://andrewlock.net/adding-cache-control-headers-to-static-files-in-asp-net-core/

No comments: