1. Nuget instala la dll correspondiente
Web API 2 : Install-Package Strathweb.CacheOutput.WebApi2 Web API 1 : Install-Package Strathweb.CacheOutput
Dos. Crea un nuevo ActionFilterAttribute y anula los métodos relacionados
clase pública WebApiOutputCacheAttribute : ActionFilterAttribute { Tiempo de caché/segundo Privado de _timespan; Tiempo de caché del cliente por segundo Private Int _clientTimeSpan; Si está almacenada en caché por usuarios anónimos Soldado Bool _anonymousOnly; Almacenar en caché la clave índice _cachekey de cadena privada; Almacenes de caché CacheObjectCache solo lectura estática privada WebApiCache = MemoryCache.Default;
Public WebApiOutputCacheAttribute(int timespan, int clientTimeSpan, bool anonymousOnly) { _timespan = periodo de tiempo; _clientTimeSpan = clienteTimeSpan; _anonymousOnly = anónimo Solo; }
//是否缓存 bool privado _isCacheable(HttpActionContext ac) { si (_timespan > 0 y _clientTimeSpan > 0) { si (_anonymousOnly) if (Thread.CurrentPrincipal.Identity.IsAuthenticated) return false; si (ac. Request.Method == HttpMethod.Get) devuelve true; } si no, { lanzar un nuevo InvalidOperationException ("Wrong Arguments"); } return false; }
private CacheControlHeaderValue setClientCache() { var cachecontrol = new CacheControlHeaderValue(); Cachecontrol. Edad máxima = TiempoEspacio. DeSegundos(_clientTimeSpan); Cachecontrol. MustRevalidate = verdadero; return cachecontrol; }
//Action调用前执行的方法 anulación pública void OnActionExecuting(HttpActionContext ac) { si (ac != nulo) { si (_isCacheable(ac)) { _cachekey = cuerda. Join(":", nueva cadena[] { ac. Request.RequestUri.AbsolutePath, ac. Request.Headers.Accept.FirstorDefault(). ToString() }); if (WebApiCache.Contains(_cachekey)) { var val = (cadena)WebApiCache.Get(_cachekey); si (val != nulo) { AC. Respuesta = CA. Request.CreateResponse(); AC. Response.Content = nuevo StringContent(val); var contenttype = (MediaTypeHeaderValue)WebApiCache.Get(_cachekey + ":response-ct"); if (contenttype == null) contenttype = nuevo MediaTypeHeaderValue(_cachekey. Split(':')[1]); AC. Response.Content.Headers.ContentType = contenttype; AC. Response.Headers.CacheControl = setClientCache(); devolución; } } } } si no, { lanzar un nuevo ArgumentNullException ("actionContext"); } }
//Action调用后执行方法 anulación pública OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { si (!( WebApiCache.Contains(_cachekey))) { var body = acciónEjecutadoContexto.Respuesta.Contenido.LeerAsStringAsync(). Resultado; WebApiCache.Add(_cachekey, cuerpo, FechaTiempo.Ahora.Añadir Segundos(_timespan)); WebApiCache.Add(_cachekey + ":response-ct", actionExecutedContext.Response.Content.Headers.ContentType, DateTime.Now.AddSeconds(_timespan)); } if (_isCacheable(acciónEjecutadoContexto.AcciónContexto)) actionExecutedContext.ActionContext.Response.Headers.CacheControl = setClientCache(); }
}
3. El controlador necesita añadir la caché al método Get para añadir el filtro
[WebApiOutputCache(120,60,false)] cadena pública GetShoppingCart() { regresar "Hola Mundo"; } Empieza, observa el punto de ruptura y observa el efecto. Todo el proceso es: inicializar el filtro de caché al inicio, luego llamar al método Get con el filtro añadido, entrar en el método OnActionExecuting, determinar si existe una caché relevante, si la hay, devolver el resultado directamente, si no, llamar a la Acción del controlador y luego llamar al método OnActionExecuted para añadir el par clave-valor de caché correspondiente y establecer el tiempo de caducidad de la caché para devolver el resultado. |