Skip to content

Instantly share code, notes, and snippets.

@AaronSadlerUK
Last active July 5, 2022 14:04
Show Gist options
  • Save AaronSadlerUK/d9fd70f40aa3d7d948b7a3158ef4b309 to your computer and use it in GitHub Desktop.
Save AaronSadlerUK/d9fd70f40aa3d7d948b7a3158ef4b309 to your computer and use it in GitHub Desktop.
Dynamic WebP Images in Umbraco V10
services.AddImageSharp(options =>
{
options.OnParseCommandsAsync = c =>
{
if (c.Context != null)
{
if (c.Context.Request.GetTypedHeaders().Accept
.Any(aValue => aValue.MediaType.Value == "image/webp"))
{
var path = c.Context.Request.Path.ToString();
if (!c.Commands.Contains("webp") || !c.Commands.Contains("noformat") && path.EndsWith("png") || path.EndsWith("jpg") || path.EndsWith("jpeg"))
{
c.Commands.Remove("format");
c.Commands.Add("format", "webp");
c.Context.Response.Headers.Add("Vary", "Accept");
}
}
}
bool doesntWantFormat = c.Commands.TryGetValue("noformat", out string value);
if (doesntWantFormat)
{
c.Commands.Remove("format");
}
return Task.CompletedTask;
};
});
}
app.UseWebP();
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
public class WebPMiddleware
{
private readonly RequestDelegate _next;
public WebPMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
if (IsImageRequest(httpContext) &&
httpContext.Request.GetTypedHeaders()?.Accept != null
&& httpContext.Request.GetTypedHeaders().Accept.Any(aValue => aValue.MediaType.Value == "image/webp"))
{
var updatedQueryString = GetUpdatedQueryString(httpContext);
var qb1 = new QueryBuilder(updatedQueryString);
httpContext.Request.QueryString = qb1.ToQueryString();
}
await _next(httpContext);
}
private bool IsImageRequest(HttpContext httpContext)
{
var path = httpContext.Request.Path.ToString();
return path.EndsWith("png") || path.EndsWith("jpg") || path.EndsWith("jpeg");
}
private List<KeyValuePair<string, string>> GetUpdatedQueryString(HttpContext httpContext)
{
var queryitems = httpContext.Request.Query.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();
var queryParameters = new List<KeyValuePair<string, string>>();
foreach (var item in queryitems)
{
var value = item.Value;
if (item.Key == "format")
{
value = "webp";
}
var newQueryParameter = new KeyValuePair<string, string>(item.Key, value);
queryParameters.Add(newQueryParameter);
}
if (!queryParameters.Any())
{
queryParameters.Add(new KeyValuePair<string, string>("format", "webp"));
}
return queryParameters;
}
}
public static class WebPMiddlewareExtensions
{
public static IApplicationBuilder UseWebP(this IApplicationBuilder builder)
{
return builder.UseMiddleware<WebPMiddleware>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment