1. Nuget installerer den relevante dll
Web API 2 : Install-Package Strathweb.CacheOutput.WebApi2 Web API 1 : Install-Package Strathweb.CacheOutput
To. Opret en ny ActionFilterAttribute og overskriv de relaterede metoder
offentlig klasse WebApiOutputCacheAttribute : ActionFilterAttribute { Cachetid/sekund privat int _timespan; Client cache time/sec privat intelligens _clientTimeSpan; Om det caches af anonyme brugere privat Bool _anonymousOnly; Cache indeksnøglen privat streng _cachekey; Cachelagre privat statisk skrivebeskyttet ObjectCache WebApiCache = MemoryCache.Default;
public WebApiOutputCacheAttribute(int timespan, int clientTimeSpan, bool anonymousOnly) { _timespan = tidsrum; _clientTimeSpan = clientTimeSpan; _anonymousOnly = anonymtKun; }
//是否缓存 private bool _isCacheable(HttpActionContext ac) { hvis (_timespan > 0 & _clientTimeSpan > 0) { hvis (_anonymousOnly) hvis (Thread.CurrentPrincipal.Identity.IsAuthenticated) return false; hvis (AC. Request.Method == HttpMethod.Get) returnerer true; } ellers { smid ny InvalidOperationException("Wrong Arguments"); } return false; }
privat CacheControlHeaderValue setClientCache() { var cachecontrol = ny CacheControlHeaderValue(); cachecontrol. MaxAge = TimeSpan.FromSeconds(_clientTimeSpan); cachecontrol. MustRevalidate = sand; returner cachecontrol; }
//Action调用前执行的方法 public override void OnActionExecuting(HttpActionContext ac) { hvis (ac != null) { hvis (_isCacheable(ac)) { _cachekey = streng. Join(":", ny streng[] { ac. Request.RequestUri.AbsolutePath, ac. Request.Headers.Accept.FirstOrDefault(). ToString() }); hvis (WebApiCache.Contains(_cachekey)) { var val = (string)WebApiCache.Get(_cachekey); hvis (val != null) { AC. Respons = ac. Request.CreateResponse(); AC. Response.Content = ny StringContent(val); var contenttype = (MediaTypeHeaderValue)WebApiCache.Get(_cachekey + ":response-ct"); hvis (contenttype == null) contenttype = ny MediaTypeHeaderValue(_cachekey. Split(':')[1]); AC. Response.Content.Headers.ContentType = contenttype; AC. Response.Headers.CacheControl = setClientCache(); vender tilbage; } } } } ellers { smid ny ArgumentNullException("actionContext"); } }
//Action调用后执行方法 offentlig override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { hvis (!( WebApiCache.Contains(_cachekey))) { var body = actionExecutedContext.Response.Content.ReadAsStringAsync(). Resultat; WebApiCache.Add(_cachekey, body, DateTime.Now.AddSeconds(_timespan)); WebApiCache.Add(_cachekey + ":response-ct", actionExecutedContext.Response.Content.Headers.ContentType, DateTime.Now.AddSeconds(_timespan)); } hvis (_isCacheable(actionExecutedContext.ActionContext)) actionExecutedContext.ActionContext.Response.Headers.CacheControl = setClientCache(); }
}
3. Controlleren skal tilføje cachen til Get-metoden for at tilføje filteret
[WebApiOutputCache(120,60,falsk)] offentlig streng GetShoppingCart() { "Hello World" tilbage; } Start, observer breakpointet, og observer effekten. Hele processen er: initialiser cachefilteret ved opstart, og kald derefter Get-metoden med filteret tilføjet, indtast OnActionExecuting-metoden, afgør om der er en relevant cache, hvis der er, returner resultatet direkte, hvis ikke, kald controllerens Action, og kald derefter OnActionExekutation-metoden for at tilføje det relevante cache-nøgle-værdi-par og sætte cachens udløbstid til at returnere resultatet. |