1. Nuget installeert de relevante dll
Web API 2 : Install-Package Strathweb.CacheOutput.WebApi2 Web API 1 : Install-Package Strathweb.CacheOutput
Twee. Maak een nieuw ActionFilterAttribuut aan en overschrijf de gerelateerde methoden
publieke klasse WebApiOutputCacheAttribute : ActionFilterAttribute { Cachetijd/sec privé-int _timespan; Client cache time/sec privé-int _clientTimeSpan; Of het wordt gecachet door anonieme gebruikers soldaat Bool _anonymousOnly; Cache de indexsleutel privé snaar _cachekey; Cache-warehouses privé statisch alleen-lezen ObjectCache WebApiCache = MemoryCache.Default;
public WebApiOutputCacheAttribute(int timespan, int clientTimeSpan, bool anonymousOnly) { _timespan = tijdsduur; _clientTimeSpan = clientTimeSpan; _anonymousOnly = anoniemAlleen; }
//是否缓存 private bool _isCacheable(HttpActionContext ac) { als (_timespan > 0 & _clientTimeSpan > 0) { als (_anonymousOnly) if (Thread.CurrentPrincipal.Identity.IsAuthenticated) return false; als (ac. Request.Method == HttpMethod.Get) return true; } anders { gooi nieuwe InvalidOperationException("Wrong Arguments"); } return false; }
private CacheControlHeaderValue setClientCache() { var cachecontrol = nieuwe CacheControlHeaderValue(); cachecontrol. MaxAge = TimeSpan.FromSeconds(_clientTimeSpan); cachecontrol. MustHervalidate = waar; terug-cachecontrol; }
//Action调用前执行的方法 public override void OnActionExecuting(HttpActionContext ac) { als (ac != null) { als (_isCacheable(ac)) { _cachekey = snaar. Join(":", nieuwe snaar[] { ac. Request.RequestUri.AbsolutePath, ac. Request.Headers.Accept.FirstOrDefault(). ToString() }); als (WebApiCache.Contains(_cachekey)) { var val = (string)WebApiCache.Get(_cachekey); als (val != nul) { AC. Respons = wisselstroom. Request.CreateResponse(); AC. Response.Content = nieuwe StringContent(val); var contenttype = (MediaTypeHeaderValue)WebApiCache.Get(_cachekey + ":response-ct"); als (contenttype == null) contenttype = nieuwe MediaTypeHeaderValue(_cachekey. Split(':')[1]); AC. Response.Content.Headers.ContentType = contenttype; AC. Response.Headers.CacheControl = setClientCache(); terugkeren; } } } } anders { gooi nieuwe ArgumentNullException("actionContext"); } }
//Action调用后执行方法 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { als (!( WebApiCache.Contains(_cachekey))) { var body = actionExecutedContext.Response.Content.ReadAsStringAsync(). Resultaat; WebApiCache.Add(_cachekey, body, DateTime.Now.AddSeconds(_timespan)); WebApiCache.Add(_cachekey + ":response-ct", actionExecutedContext.Response.Content.Headers.ContentType, DateTime.Now.AddSeconds(_timespan)); } als (_isCacheable(actionExecutedContext.ActionContext)) actionExecutedContext.ActionContext.Response.Headers.CacheControl = setClientCache(); }
}
3. De controller moet de cache toevoegen aan de Get-methode om het filter toe te voegen
[WebApiOutputCache(120,60,false)] publieke string GetShoppingCart() { keer "Hello World" terug; } Begin, observeer het breekpunt en observeer het effect. Het hele proces bestaat uit: initialiseer het cachefilter bij het opstarten, roep dan de Get-methode aan met het toegevoegde filter, voer de OnActionExecuting-methode in, bepaal of er een relevante cache is, indien die er is, geef het resultaat direct terug, zo niet, roep dan de Actie van de controller aan, en roep vervolgens de OnActionExekut-methode aan om het relevante cache-sleutel-waardepaar toe te voegen en de vervaldatum van de cache in te stellen om het resultaat terug te geven. |