diff --git a/src/Middleware/OutputCaching/src/OutputCacheMiddleware.cs b/src/Middleware/OutputCaching/src/OutputCacheMiddleware.cs index 0fb2d123ca20..76b0bdb75e2d 100644 --- a/src/Middleware/OutputCaching/src/OutputCacheMiddleware.cs +++ b/src/Middleware/OutputCaching/src/OutputCacheMiddleware.cs @@ -119,6 +119,8 @@ private async Task InvokeAwaited(HttpContext httpContext, IReadOnlyList + { + builder.AddPolicy(new RefreshableCachePolicy()); + builder.Cache(); + }, true); + + var cache = new TestOutputCache(); + var sink = new TestSink(); + var middleware = TestUtils.CreateTestMiddleware(options: options, testSink: sink, cache: cache, next: async c => + { + await c.Response.WriteAsync(Guid.NewGuid().ToString()); + }); + + // Act - Four requests are executed. The third request + // should trigger a cache refresh so that the first two requests + // have matching output, and the last two have matching output. + var initialResponse = await SendRequestAsync(includeRefreshHeader: false); + var cachedResponse = await SendRequestAsync(includeRefreshHeader: false); + var refreshedResponse = await SendRequestAsync(includeRefreshHeader: true); + var cachedResponseAfterRefresh = await SendRequestAsync(includeRefreshHeader: false); + + Assert.Equal(initialResponse, cachedResponse); + Assert.NotEqual(cachedResponse, refreshedResponse); + Assert.Equal(refreshedResponse, cachedResponseAfterRefresh); + + async Task SendRequestAsync(bool includeRefreshHeader) + { + var requestContext = TestUtils.CreateTestContext(cache: cache); + requestContext.HttpContext.Request.Method = "GET"; + requestContext.HttpContext.Request.Path = "/"; + var responseStream = new MemoryStream(); + requestContext.HttpContext.Response.Body = responseStream; + + if (includeRefreshHeader) + { + requestContext.HttpContext.Request.Headers.Add("X-Refresh", "randomvalue"); + } + + await middleware.Invoke(requestContext.HttpContext); + var response = Encoding.UTF8.GetString(responseStream.GetBuffer()); + return response; + } + } }