Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the headers of static files in Asp.net Core

I am using package Microsoft.AspNet.StaticFiles and configuring it in Startup.cs as app.UseStaticFiles(). How can I change the headers of the delivered files ? I want to set cache expiry etc for images, css and js.

like image 864
eadam Avatar asked Mar 25 '15 12:03

eadam


1 Answers

You can use StaticFileOptions, which contains an event handler that is called on each request of a static file.

Your Startup.cs should look something like this:

// Add static files to the request pipeline.
app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = (context) =>
    {
        // Disable caching of all static files.
        context.Context.Response.Headers["Cache-Control"] = "no-cache, no-store";
        context.Context.Response.Headers["Pragma"] = "no-cache";
        context.Context.Response.Headers["Expires"] = "-1";
    }
});

You can, of course, modify the above code to check the content type and only modify headers for JS or CSS or whatever you want.

like image 84
Josh Mouch Avatar answered Sep 19 '22 21:09

Josh Mouch