1. Nuget installerer relevant dll
Web API 2 : Install-Package Strathweb.CacheOutput.WebApi2 Web API 1 : Install-Package Strathweb.CacheOutput
To. Opprett et nytt ActionFilterAttribut og overstyr de relaterte metodene
offentlig klasse WebApiOutputCacheAttribute : ActionFilterAttribute { Cache-tid/sekund privat intelligens _timespan; Client cache time/sec privat intelligens _clientTimeSpan; Om den er cachet av anonyme brukere menig Bool _anonymousOnly; Cache indeksnøkkelen privat streng _cachekey; Cache-lagre privat statisk skrivebeskyttet ObjectCache WebApiCache = MemoryCache.Default;
public WebApiOutputCacheAttribute(int timespan, int clientTimeSpan, bool anonymousOnly) { _timespan = tidsspenn; _clientTimeSpan = clientTimeSpan; _anonymousOnly = anonymKun; }
//是否缓存 privat bool _isCacheable(HttpActionContext ac) { hvis (_timespan > 0 & _clientTimeSpan > 0) { hvis (_anonymousOnly) hvis (Thread.CurrentPrincipal.Identity.IsAuthenticated) returner falsk; hvis (AC. Request.Method == HttpMethod.Get) returnerer true; } ellers { kast ny InvalidOperationException("Wrong Arguments"); } returner falsk; }
privat CacheControlHeaderValue setClientCache() { var cachecontrol = ny CacheControlHeaderValue(); cachecontrol. MaxAge = TimeSpan.FromSeconds(_clientTimeSpan); cachecontrol. MustRevalidate = true; returner cachecontrol; }
//Action调用前执行的方法 offentlig 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 (innholdstype == null) contenttype = ny MediaTypeHeaderValue(_cachekey. Split(':')[1]); AC. Response.Content.Headers.ContentType = contenttype; AC. Response.Headers.CacheControl = setClientCache(); returnere; } } } } ellers { kast 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. Kontrolleren må legge til cachen i Get-metoden for å legge til filteret
[WebApiOutputCache(120,60,falsk)] offentlig streng GetShoppingCart() { returnerer "Hello World"; } Start, observer brytepunktet, og observer effekten. Hele prosessen går ut på: initialiser cache-filteret ved oppstart, og kaller deretter Get-metoden med filteret lagt til, legg inn OnActionExecuting-metoden, avgjør om det finnes en relevant cache, hvis det finnes, returner resultatet direkte, hvis ikke, kall kontrollerens Action, og deretter OnActionExecuted-metoden for å legge til det relevante cache-nøkkel-verdi-paret og sett cache-utløpstiden til å returnere resultatet. |