Skip to content

Instantly share code, notes, and snippets.

@mmols
Created April 1, 2018 18:48
Simple ActionFilter demonstrating adding CacheControl headers in Episerver Content Delivery Api
using EPiServer.ContentApi.Controllers;
using EPiServer.ContentApi.Search.Controllers;
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http.Filters;
namespace Alloy.Business
{
public class ContentDeliveryApiCacheActionFilter : ActionFilterAttribute, IFilter
{
private static readonly Type[] contentDeliveryApiControllers = new Type[]
{
typeof(ContentApiController),
typeof(ContentApiSearchController),
typeof(SiteDefinitionApiController)
};
public override void OnActionExecuted(HttpActionExecutedContext context)
{
if (IsContentDeliveryApiRequest(context) && context.Response.IsSuccessStatusCode)
{
var requestIsAnonymous = !context.Request.GetRequestContext().Principal.Identity.IsAuthenticated;
if (requestIsAnonymous)
{
context.Response.Headers.CacheControl = new CacheControlHeaderValue()
{
Public = true,
MaxAge = new TimeSpan(1, 0, 0, 0),
};
}
}
base.OnActionExecuted(context);
}
private bool IsContentDeliveryApiRequest(HttpActionExecutedContext context)
{
var controllerType = context.ActionContext.ControllerContext.ControllerDescriptor.ControllerType;
return contentDeliveryApiControllers.Contains(controllerType);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment