Cache-Control JSS / JS Files in Server Side Blazor

Viewed 410

I want to improve browser caching in case of writing Cache-Control max-age Header attribute. For this i found this helpful page: https://www.meziantou.net/caching-static-resources-forever-with-asp-net-core.htm

But when trying this in Server Side Blazor the whole application stops running.

As long as I use the following code (also if not JS is filtered) the Blazor app won't run:

            app.UseStaticFiles(new StaticFileOptions()
        {
            OnPrepareResponse =
                r =>
                {
                    string path = r.File.PhysicalPath;
                    if (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"));
                    }
                }
        });

Browser F12 view:

enter image description here

Any idea what causes this and how to fix it (use Cache-Control for all but the important Blazor JS files) ?

1 Answers

I ran into the same problem and found the solution here

You can either call UseStaticFiles() again after setting your cache control headers

app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = r =>
    {
        string path = r.File.PhysicalPath;
        if (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"));
        }
    }
});
app.UseStaticFiles();

or configure StaticFileOptions in ConfigureServices.

services.Configure<StaticFileOptions>(opts =>
{
    opts.OnPrepareResponse = ctx =>
    {
        string path = r.File.PhysicalPath;
        if (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"));
        }
    };
});
Related