1. Nuget installa il dll pertinente
Web API 2 : Install-Package Strathweb.CacheOutput.WebApi2 Web API 1 : Install-Package Strathweb.CacheOutput
Due. Crea un nuovo ActionFilterAttribute e sovrascrivi i metodi correlati
classe pubblica WebApiOutputCacheAttribute : ActionFilterAttribute { Tempo di cache/secondo Private Int _timespan; Tempo di cache del client per secondo Private Int _clientTimeSpan; Se viene memorizzato nella cache da utenti anonimi Privato Bool _anonymousOnly; Memorizza la chiave indice nella cache _cachekey di corda privata; Magazzini di cache privato statico ObjectCache WebApiCache = MemoryCache.Default;
pubblica WebApiOutputCacheAttribute(int timespan, int clientTimeSpan, bool anonymousOnly) { _timespan = arco temporale; _clientTimeSpan = clienteTimeSpan; _anonymousOnly = anonimoSolo; }
//是否缓存 bool privato _isCacheable(HttpActionContext ac) { se (_timespan > 0 e _clientTimeSpan > 0) { se (_anonymousOnly) if (Thread.CurrentPrincipal.Identity.IsAuthenticated) return false; se (ac. Request.Method == HttpMethod.Get) restituisce true; } altrimenti { lanciare nuovi InvalidOperationException ("Argomenti Sbagliati"); } return false; }
private CacheControlHeaderValue setClientCache() { var cachecontrol = new CacheControlHeaderValue(); Controllo della cache. MaxEtà = TempoIntervallo. DaSecondi(_clientTimeSpan); Controllo della cache. MustRevalidate = vero; return cachecontrol; }
//Action调用前执行的方法 override pubblico void OnActionExecuting(HttpActionContext ac) { se (ac != nullo) { if (_isCacheable(ac)) { _cachekey = filo. Join(":", nuova stringa[] { ac. Request.RequestUri.AbsolutePath, ac. Request.Headers.Accept.FirstorDefault(). ToString() }); if (WebApiCache.Contains(_cachekey)) { var val = (stringa)WebApiCache.Get(_cachekey); se (val != null) { AC. Risposta = ac. Request.CreateResponse(); AC. Response.Content = nuovo StringContent(val); var contenttype = (MediaTypeHeaderValue)WebApiCache.Get(_cachekey + ":response-ct"); if (contenttype == null) contenttype = nuovo MediaTypeHeaderValue(_cachekey. Split(':')[1]); AC. Response.Content.Headers.ContentType = contenttype; AC. Response.Headers.CacheControl = setClientCache(); ritorno; } } } } altrimenti { lanciare un nuovo ArgumentNullException ("actionContext"); } }
//Action调用后执行方法 override pubblico void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { se (!( WebApiCache.Contains(_cachekey))) { var body = actionExecutedContext.Response.Content.ReadAsStringAsync(). Risultato; WebApiCache.Add(_cachekey, corpo, 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. Il controller deve aggiungere la cache al metodo Get per aggiungere il filtro
[WebApiOutputCache(120,60,false)] stringa pubblica GetShoppingCart() { ritorno "Hello World"; } Inizia, osserva il punto di rottura e osserva l'effetto. L'intero processo è: inizializza il filtro della cache all'avvio, poi chiama il metodo Get con il filtro aggiunto, entra nel metodo OnActionExecuting, determina se esiste una cache rilevante, se c'è, restituisci direttamente il risultato, altrimenti chiami l'Action del controller, e poi chiami il metodo OnActionExecuted per aggiungere la coppia chiave-valore della cache pertinente e imposta il tempo di scadenza della cache per restituire il risultato. |