Created
February 23, 2012 16:33
-
-
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
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
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Won't compile. There is no property
Result
inHttpActionExecutedContext