Created
September 22, 2022 11:13
-
-
Save warrenbuckley/344ea0317a9fcf323f172e239015921f to your computer and use it in GitHub Desktop.
Showing how to use ASP.NET Static Assets options to set custom headers on files with Umbraco
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.Net.Http.Headers; | |
using Umbraco.Cms.Core.Composing; | |
namespace StaticAssets | |
{ | |
public class StaticAssetsHeaders : IComposer | |
{ | |
public void Compose(IUmbracoBuilder builder) | |
{ | |
builder.Services.Configure<StaticFileOptions>(options => | |
{ | |
options.OnPrepareResponse = ctx => | |
{ | |
// Need to ignore static assets in Umbraco backoffice | |
// Where the request path starts with umbraco | |
// Example.. | |
// /umbraco/lib/font-awesome/css/font-awesome.min.css | |
// /umbraco/js/init.min.js | |
if (ctx.Context.Request.Path.StartsWithSegments("/umbraco")) | |
{ | |
return; | |
} | |
// NOTE !! | |
// Images from CMS media pickers that do not use Image Processor will come through here too | |
// <img src="@Model.ImagePicker.Url()" /> | |
// Set all static file requests | |
// To have Allow any origin for CORS requests | |
ctx.Context.Response.Headers.Append(HeaderNames.AccessControlAllowOrigin, "*"); | |
// Just a custom made up header with a date in | |
ctx.Context.Response.Headers.Append("x-custom-header-date", DateTime.Now.ToString("o")); | |
// Certain file extensions | |
var fileExtension = Path.GetExtension(ctx.File.Name); | |
if (fileExtension == ".svg") | |
{ | |
// Set a specific Cache header | |
var typedHeaders = ctx.Context.Response.GetTypedHeaders(); | |
// Update or set Cache-Control header | |
var cacheControl = typedHeaders.CacheControl ?? new CacheControlHeaderValue(); | |
cacheControl.Public = true; | |
cacheControl.MaxAge = TimeSpan.FromMinutes(1); | |
typedHeaders.CacheControl = cacheControl; | |
} | |
// Other ideas | |
// Add specific cache headers if a static file was served from a specific folder | |
// Such as wwwroot/assets regardless of extension | |
}; | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment