- private const intCACHE_SECONDS =30;
- private readonlyDictionary<string, Tupleint>> cachedResponses =newDictionary<string, Tupleint>>();
- protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
- {
- base.ApplicationStartup(container, pipelines);
- pipelines.BeforeRequest += CheckCache;
- pipelines.AfterRequest += SetCache;
- }
- //检查我们是否有缓存条目-如果我们做了, 看看它是否已经过期,
- //如果没有返回, 否则返回 null;
- public Response CheckCache(NancyContext context)
- {
- Tupleint> cacheEntry;
- if(this.cachedResponses.TryGetValue(context.Request.Path,out cacheEntry))
- {
- if(cacheEntry.Item1.AddSeconds(cacheEntry.Item3)>DateTime.Now)
- {
- return cacheEntry.Item2;
- }
- }
- return null;
- }
- //如果需要, 将当前响应添加到缓存中
- //仅按路径存储, 并将响应存储在字典中。
- //不要将此作为实际缓存:-)
- public void SetCache(NancyContext contexts)
- {
- if(contexts.Response.StatusCode!=HttpStatusCode.OK)
- {
- return;
- }
- object cacheSecondsObject;
- if(!contexts.Items.TryGetValue(ContextExtensions.OUTPUT_CACHE_TIME_KEY,out cacheSecondsObject))
- {
- return;
- }
- int cacheSeconds;
- if(!int.TryParse(cacheSecondsObject.ToString(),out cacheSeconds))
- {
- return;
- }
- varcachedResponse =new CachedResponse(contexts.Response);
- this.cachedResponses[contexts.Request.Path]=newTupleint>(DateTime.Now,cachedResponse,cacheSeconds);
- contexts.Response = cachedResponse;
- }
来源: http://www.cnblogs.com/R00R/p/6863134.html