1. Nuget telepíti a megfelelő DLL-t
Web API 2 : Install-Package Strathweb.CacheOutput.WebApi2 Web API 1: install-package Strathweb.CacheOutput
Kettő. Hozz létre egy új ActionFilterAttribute-t, és felülírd a kapcsolódó metódusok
public class WebApiOutputCacheAttribute : ActionFilterAttribute { Gyorsítótár idő/másodperc privát int _timespan; Kliens gyorsítótár idő/másodperc privát int _clientTimeSpan; Akár anonim felhasználók is gyorsítótározzák Bool _anonymousOnly közlegény; Gyorsítótár az index kulcsot privát String _cachekey; Raktárraktárak privát statikus readonly ObjectCache WebApiCache = MemoryCache.Default;
public WebApiOutputCacheAttribute(int timespan, int clientTimeSpan, bool anonymousOnly) { _timespan = időintervall; _clientTimeSpan = clientTimeSpan; _anonymousOnly = anonymousOnly; }
//是否缓存 private bool _isCacheable(HttpActionContext ac) { ha (_timespan > 0 && _clientTimeSpan > 0) { if (_anonymousOnly) if (Thread.CurrentPrincipal.Identity.IsAuthenticated) hamis; ha (AC. Request.Method == HttpMethod.Get) tér vissza igazat; } más { dobjuk az új InvalidOperationException ("Wrong Arguments"); } hamis; }
privát CacheControlHeaderValue setClientCache() { var cachecontrol = új CacheControlHeaderValue(); Cache Control. MaxAge = TimeSpan.FromSeconds(_clientTimeSpan); Cache Control. MustRevalidate = true; return cachecontrol; }
//Action调用前执行的方法 public override void OnActionExecuting(HttpActionContext ac) { ha (ac != null) { if (_isCacheable(ac)) { _cachekey = húr. Join(":", új string[] { ac. Request.RequestUri.AbsolutePath, ac. Request.Headers.Accept.FirstOrDefault(). ToString() }); if (WebApiCache.Contains(_cachekey)) { var val = (string)WebApiCache.Get(_cachekey); if (val != null) { AC. Válasz = ac. Request.CreateResponse(); AC. Response.Content = új StringContent(val); var contenttype = (MediaTypeHeaderValue)WebApiCache.Get(_cachekey + ":response-ct"); if (contenttype == null) contenttype = new MediaTypeHeaderValue(_cachekey. Split(':')[1]); AC. Response.Content.Headers.ContentType = contenttype; AC. Response.Headers.CacheControl = setClientCache(); visszatérés; } } } } más { dobjuk új ArgumentNullException("actionContext"); } }
//Action调用后执行方法 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { ha (!( WebApiCache.Contains(_cachekey)))) { var body = actionExecutedContext.Response.Content.ReadAsStringAsync(). Eredmény; WebApiCache.Add(_cachekey, body, DateTime.Now.AddSeconds(_timespan)); WebApiCache.Add(_cachekey + ":response-ct", actionExecutedContext.Response.Content.Headers.ContentType, DateTime.Now.AddSeconds(_timespan)); } if (_isCacheable(actionExecutedContext.ActionContext)) actionExecutedContext.ActionContext.Response.Headers.CacheControl = setClientCache(); }
}
3. A vezérlőnek hozzá kell adnia a gyorsítótárt a Get metódushoz a szűrő hozzáadásához
[WebApiOutputCache(120,60,hamis)] nyilvános string GetShoppingCart() { visszatér a "Hello World"; } Kezdjük, figyeld meg a töréspontot, és figyeld meg a hatást. Az egész folyamat a következő: inicializálni a gyorsítótárszűrőt indításkor, majd a Get metódusot a szűrővel beállítva, belépni az OnActionExecuting metódusba, megállapítani, van-e releváns gyorsítótár, ha van, közvetlenül visszaküldeni az eredményt, ha nincs, hívjuk meg a kontroller Action-ját, majd hívjuk az OnActionExecuted metódust, hogy hozzáadjuk a megfelelő cache kulcs-érték párt, és beállítsuk a cache lejárati idejét, hogy visszaadja az eredményt. |