Over a million developers have joined DZone.

Add HTTP Headers to Static Files in ASP.NET Core

DZone's Guide to

Add HTTP Headers to Static Files in ASP.NET Core

In this article we have a look at how to modify the headers in static files in ASP.NET Core. Sometimes you just have to disable a cache!

· Web Dev Zone
Free Resource

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

Usually, static files like JavaScript, CSS, images, and so on, are cached on the client after the first request. But sometimes, you need to disable the cache or to add a special cache handling.

To provide static files in an ASP.NET Core application, you use the StaticFileMiddleware:


This extension method has two overloads. One of them needs a StaticFileOptions instance, which is our friend in this case. This option has a property called OnPrepareResponse of type Action<StaticFileResponseContext>. Inside this action, you have access to the HttpContext and many more. Let's see how it looks like to set the cache lifetime to 12 hours:

app.UseStaticFiles(new StaticFileOptions()
    OnPrepareResponse = context =>
        context.Context.Response.Headers["Cache-Control"] = 
                "private, max-age=43200";

        context.Context.Response.Headers["Expires"] = 

With the StaticFileResponseContext, you also have access to the file of the currently handled file. With this info, it is possible to manipulate the HTTP headers just for a specific file or file type.

This approach ensures that the client doesn't use pretty much outdated files, but uses cached versions while working with it. We use this in an ASP.NET Core single page application, which uses many JavaScript and HTML template files. In combination with continuous deployment, we need to ensure the application uses the latest files.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

headers ,static ,http ,core ,files ,asp.net

Published at DZone with permission of Juergen Gutsch, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}