How to cache css,js or images files to asp.net core

app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse =
        r =>
        {
            string path = r.File.PhysicalPath;
            if (path.EndsWith(".css") || path.EndsWith(".js") || path.EndsWith(".gif") || path.EndsWith(".jpg") || path.EndsWith(".png") || path.EndsWith(".svg"))
            {
                TimeSpan maxAge = new TimeSpan(7, 0, 0, 0);
                r.Context.Response.Headers.Append("Cache-Control", "max-age=" + maxAge.TotalSeconds.ToString("0"));
            }
        }
});

Here is an approach that should work for you. This example sets css and js files to be cached for 7 days by the browser and sets non css, js, and images to have no cache headers. One other note, it's only necessary to set the cache control headers on the response is Asp.NET Core.

        app.Use(async (context, next) =>
        {
            string path = context.Request.Path;

            if(path.EndsWith(".css") || path.EndsWith(".js")) {

                //Set css and js files to be cached for 7 days
                TimeSpan maxAge = new TimeSpan(7, 0, 0, 0);     //7 days
                context.Response.Headers.Append("Cache-Control", "max-age="+ maxAge.TotalSeconds.ToString("0")); 

            } else if(path.EndsWith(".gif") || path.EndsWith(".jpg") || path.EndsWith(".png")) {
                //custom headers for images goes here if needed

            } else {
                //Request for views fall here.
                context.Response.Headers.Append("Cache-Control", "no-cache");
                context.Response.Headers.Append("Cache-Control", "private, no-store");

            }
            await next();
        });

Another solution via app.UseStaticFiles

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

You must add this library ;

using Microsoft.Net.Http.Headers;