How to Use Cache Headers with Static Middleware in .NET Applications – Windows ASP.NET Core Hosting 2024 | Review and Comparison

How to Use Cache Headers with Static Middleware in .NET Applications

In this article, we will have a look at http cache headers and how they can be configured while serving static files middleware.

Cache-Control Header

Now a days, every software solution has some components which are hosted on web. They interact with one another using HTTP requests. Every business is on internet. One of the important factor to retain users is how good the website is, how quickly it responds to user’s requests.

Every request that is issued from web application needs some time for its processing. One of the major factor that contributes to this time is network latency. Network latency is just a fancy name to the total time between issuing a web request and getting the response from the web server.

There are multiple solutions to reduce the network latency for any web applications. Deployment servers can be nearer to the physical locations of users to reduce the request travel time. Other solution can be to enable caching of requests and responses.

Application can have its own layer of caching on client side. Application can also rely on cache-control header for at least some of the resources, provided the application is being accessed from a browser.

What does it do ?

The cache-control header instructs the browsers to cache (or not cache) requests and responses for configured duration of time. There is a lot of information available about this response header.

A response that is marked as public means it can be cached at any level. In most of the cases it is not necessary to specify this. Even if this type of response is associated with any error code or http auth errors, the response would still be cached just because it was marked as public.

A response can also be marked as private. It means the response provided by server is specific to a user and hence it should not be cached at any intermediate level. But it can or should be certainly be cached in the browser.

The max-age directive states the maximum amount of time in seconds that fetched responses are allowed to be used again. For example below code states that the same response can be used for next 10 seconds. Also it is public, so it can be cached at all levels (CDN, proxy servers, browsers, etc.).

Cache-Control: public, max-age=10

Static Files Middleware

Static files middleware can be used to set the response headers. UseStaticFiles middleware takes StaticFileOptions as parameter, which has OnPrepareResponse delegate. It can be set to logic which would set response headers.

Below is example code which shows how to set cache-control response header via Static Files middleware. The code is setting response headers for all images under images folder.

public class Startup
{
    // Some other code...
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // some middlewares...
        
        // Files from default wwwroot folder, no specific response header added.
        app.UseStaticFiles();

        // For images under {content-root}/Images folder
        // Responses would be cached for 7 days
        const string cacheMaxAge = "604800";
        string imagesFolderPath = Path.Combine(env.ContentRootPath, "Images");
        
        app.UseStaticFiles(new StaticFileOptions
        {

            FileProvider = new PhysicalFileProvider(imagesFolderPath),
            RequestPath = "/images",
            OnPrepareResponse = ctx =>
            {
                // using Microsoft.AspNetCore.Http;
                ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cacheMaxAge}");
            }
        });
      
        // some other middlewares...
    }
}

Have you used response headers with static files ? Let me know what was your way of get it working.