/// <summary> /// 转储并缓存响应 /// </summary> /// <param name="executingContext"></param> /// <param name="next"></param> /// <param name="key"></param> /// <returns></returns> protected async Task <ResponseCacheEntry?> DumpAndCacheResponseAsync(ResourceExecutingContext executingContext, ResourceExecutionDelegate next, string key) { var response = executingContext.HttpContext.Response; var originalBody = response.Body; using var dumpStream = executingContext.HttpContext.RequestServices.GetRequiredService <IResponseDumpStreamFactory>().Create(Context.DumpStreamCapacity); ResponseCacheEntry cacheEntry = null !; ResourceExecutedContext executedContext; try { response.Body = dumpStream; CachingDiagnostics.NoCachingFounded(key, executingContext, Context); executedContext = await next(); dumpStream.Position = 0; await dumpStream.CopyToAsync(originalBody); cacheEntry = new ResponseCacheEntry(response.ContentType, dumpStream.ToArray().AsMemory(), Context.Duration); } finally { response.Body = originalBody; } return(await CheckAndStoreCacheAsync(executingContext, executedContext, key, cacheEntry)); }
private async Task InternalOnResourceExecutionAsync(ResourceExecutingContext executingContext, ResourceExecutionDelegate next, CachingDiagnostics cachingDiagnostics) { cachingDiagnostics.StartProcessingCache(executingContext, Context); try { var key = (await Context.KeyGenerator.GenerateKeyAsync(executingContext)).ToLowerInvariant(); cachingDiagnostics.CacheKeyGenerated(executingContext, key, Context.KeyGenerator, Context); if (key.Length > Context.MaxCacheKeyLength) { cachingDiagnostics.CacheKeyTooLong(key, Context.MaxCacheKeyLength, executingContext, Context); await next(); return; } if (string.IsNullOrEmpty(key)) { cachingDiagnostics.NoCachingFounded(key, executingContext, Context); await next(); return; } if (await TryServeFromCacheAsync(executingContext, key)) { return; } await ExecutingRequestAsync(executingContext, next, key); } finally { cachingDiagnostics.EndProcessingCache(executingContext, Context); } }