Created
April 1, 2018 18:48
Simple ActionFilter demonstrating adding CacheControl headers in Episerver Content Delivery Api
This file contains hidden or 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 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