Skip to content

Instantly share code, notes, and snippets.

@DavidDeSloovere
Created February 23, 2012 16:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidDeSloovere/1893621 to your computer and use it in GitHub Desktop.
Save DavidDeSloovere/1893621 to your computer and use it in GitHub Desktop.
Sample CacheAttribute for ASP.NET Web Api - i'm not saying this is the best way
namespace ProjectName.WebApi.Infrastructure
{
using System;
using System.Net;
using System.Net.Http.Headers;
using System.Web.Http.Filters;
public class CacheAttribute : ActionFilterAttribute
{
public CacheAttribute()
{
this.Days = 30;
}
public int Days { get; set; }
public int Hours { get; set; }
public int Minutes { get; set; }
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// actionExecutedContext.Result can be null if there was an exception in the controller
if (actionExecutedContext.Result != null && actionExecutedContext.Result.StatusCode == HttpStatusCode.OK)
{
actionExecutedContext.Result.Headers.Vary.Add("Accept");
actionExecutedContext.Result.Headers.Vary.Add("Accept-Language");
if (actionExecutedContext.Result.Headers.CacheControl == null)
{
actionExecutedContext.Result.Headers.CacheControl = new CacheControlHeaderValue { Private = true, Public = true};
}
var timespan = new TimeSpan(this.Days, this.Hours, this.Minutes, 0);
actionExecutedContext.Result.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.Add(timespan));
}
base.OnActionExecuted(actionExecutedContext);
}
}
}
@vmeln
Copy link

vmeln commented Jun 24, 2015

Won't compile. There is no property Result in HttpActionExecutedContext

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment