Example class to allow the modification of the Cache-Control header for static assets by file extension, but excluding Umbraco BackOffice assets.
usingSystem.IO;usingSystem;usingSystem.Collections.Generic;usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Http;usingMicrosoft.Extensions.Options;usingMicrosoft.AspNetCore.Http.Headers;usingMicrosoft.Net.Http.Headers;usingUmbraco.Cms.Core.Configuration.Models;usingIHostingEnvironment=Umbraco.Cms.Core.Hosting.IHostingEnvironment;namespaceUmbraco.Docs.Samples.Web.Tutorials;publicclassConfigureStaticFileOptions:IConfigureOptions<StaticFileOptions>{ // These are the extensions of the file types we want to cache (add and remove as you see fit)privatestaticreadonlyHashSet<string> _cachedFileExtensions =new(StringComparer.OrdinalIgnoreCase) {".ico",".css",".js",".svg",".woff2",".jpg" };privatereadonlystring _backOfficePath;publicConfigureStaticFileOptions(IOptions<GlobalSettings> globalSettings,IHostingEnvironment hostingEnvironment)=> _backOfficePath =globalSettings.Value.GetBackOfficePath(hostingEnvironment);publicvoidConfigure(StaticFileOptions options)=>options.OnPrepareResponse= ctx => { // Exclude Umbraco backoffice assetsif (ctx.Context.Request.Path.StartsWithSegments(_backOfficePath)) {return; } // Set headers for specific file extensionsvar fileExtension =Path.GetExtension(ctx.File.Name);if (_cachedFileExtensions.Contains(fileExtension)) {ResponseHeaders headers =ctx.Context.Response.GetTypedHeaders(); // Update or set Cache-Control headerCacheControlHeaderValue cacheControl =headers.CacheControl??newCacheControlHeaderValue();cacheControl.Public=true;cacheControl.MaxAge=TimeSpan.FromDays(365);headers.CacheControl= cacheControl; } };}
Modify the Cache-Control header for ImageSharp.Web
For setting Cache-Control max-age header for images processed by the ImageSharp middleware, you can set the Umbraco:CMS:Imaging:Cache:BrowserMaxAge setting.