1. Nuget이 해당 DLL을 설치합니다
Web API 2 : Install-Package Strathweb.CacheOutput.WebApi2 웹 API 1 : 설치-패키지 Strathweb.CacheOutput
2. 새로운 ActionFilterAttribute를 만들고 관련 메서드를 덮어쓰세요
public class WebApiOutputCacheAttribute : ActionFilterAttribute { 캐시 시간/초 사설 정보 _timespan; 클라이언트 캐시 시간/초 사설 _clientTimeSpan; 익명 사용자가 캐시하는지 여부 불 사병 _anonymousOnly; 인덱스 키를 캐시하세요 사적 _cachekey; 캐시 창고 개인 정적 읽기 전용 ObjectCache WebApiCache = MemoryCache.Default;
public WebApiOutputCacheAttribute(int timespan, int clientTimeSpan, bool anonymousOnly) { _timespan = 시간 간격; _clientTimeSpan = clientTimeSpan; _anonymousOnly = 익명성; }
//是否缓存 private bool _isCacheable(HttpActionContext ac) { 만약 (_timespan > 0 & _clientTimeSpan > 0) { 만약 (_anonymousOnly) if (Thread.CurrentPrincipal.Identity.IsAuthenticated) return false; 만약 (ac. Request.Method == HttpMethod.Get) true를 반환합니다; } 그렇지 않으면 { 새로운 InvalidOperationException("Wrong Arguments")를 throw합니다; } return false; }
private CacheControlHeaderValue setClientCache() { var cachecontrol = new CacheControlHeaderValue(); 캐시컨트롤. MaxAge = TimeSpan.FromSeconds(_clientTimeSpan); 캐시컨트롤. MustRevalidate = 참; 캐시컨트롤을 반환; }
//Action调用前执行的方法 public override void OnActionExecuting(HttpActionContext ac) { 만약 (ac != null) { 만약 (_isCacheable(ac)) { _cachekey = 끈. Join(":", 새 문자열[] { ac. 요청.요청 유리.절대경로, ac. Request.Headers.Accept.FirstOrDefault(). ToString() }); if (WebApiCache.Contains(_cachekey)) { var val = (string)WebApiCache.Get(_cachekey); 만약 (val != null) { 에어컨. 응답 = ac. Request.CreateResponse(); 에어컨. Response.Content = 새로운 StringContent(val); var contenttype = (MediaTypeHeaderValue)WebApiCache.Get(_cachekey + ":response-ct"); 만약 (contenttype == null) contenttype = new MediaTypeHeaderValue(_cachekey. Split(':')[1]); 에어컨. Response.Content.Headers.ContentType = contentType; 에어컨. Response.Headers.CacheControl = setClientCache(); 복귀; } } } } 그렇지 않으면 { 새로운 ArgumentNullException("actionContext"); } }
//Action调用后执行方法 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) { 만약 (!( WebApiCache.Contains(_cachekey))) { var body = actionExecutedContext.Response.Content.ReadAsStringAsync(). 결과; WebApiCache.Add(_cachekey, 본문, 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. 컨트롤러가 필터를 추가하기 위해 Get 메서드에 캐시를 추가해야 합니다
[WebApiOutputCache(120,60,false)] 공개 문자열 GetShoppingCart() { "Hello World"를 다시 받아; } 시작하고, 브레이크포인트를 관찰하고, 그 효과를 관찰하세요. 전체 과정은 다음과 같습니다: 시작 시 캐시 필터를 초기화한 후 필터를 추가한 Get 메서드를 호출하고, OnActionExecuting 메서드를 입력하여 관련 캐시가 있는지 확인하고, 있다면 결과를 직접 반환하고, 없다면 컨트롤러의 Action을 호출한 뒤, OnActionExecuted 메서드를 호출하여 해당 캐시 키값 쌍을 추가하고 캐시 만료 시간을 설정하여 결과를 반환합니다. |