Skip to content
This repository was archived by the owner on Nov 22, 2018. It is now read-only.

Commit 8699f47

Browse files
committed
Overwrite headers when serving response from cache #101
1 parent a6909cc commit 8699f47

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

src/Microsoft.AspNetCore.ResponseCaching/ResponseCachingMiddleware.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ internal async Task<bool> TryServeCachedResponseAsync(ResponseCachingContext con
149149
response.StatusCode = context.CachedResponse.StatusCode;
150150
foreach (var header in context.CachedResponse.Headers)
151151
{
152-
response.Headers.Add(header);
152+
response.Headers[header.Key] = header.Value;
153153
}
154154

155155
response.Headers[HeaderNames.Age] = context.CachedEntryAge.Value.TotalSeconds.ToString("F0", CultureInfo.InvariantCulture);
@@ -280,7 +280,7 @@ internal async Task FinalizeCacheHeadersAsync(ResponseCachingContext context)
280280
{
281281
if (!string.Equals(header.Key, HeaderNames.Age, StringComparison.OrdinalIgnoreCase))
282282
{
283-
context.CachedResponse.Headers.Add(header);
283+
context.CachedResponse.Headers[header.Key] = header.Value;
284284
}
285285
}
286286
}

test/Microsoft.AspNetCore.ResponseCaching.Tests/ResponseCachingMiddlewareTests.cs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,35 @@ await cache.SetAsync(
7575
LoggedMessage.CachedResponseServed);
7676
}
7777

78+
[Fact]
79+
public async Task TryServeFromCacheAsync_CachedResponseFound_OverwritesExistingHeaders()
80+
{
81+
var cache = new TestResponseCache();
82+
var sink = new TestSink();
83+
var middleware = TestUtils.CreateTestMiddleware(testSink: sink, cache: cache, keyProvider: new TestResponseCachingKeyProvider("BaseKey"));
84+
var context = TestUtils.CreateTestContext();
85+
86+
context.HttpContext.Response.Headers["MyHeader"] = "OldValue";
87+
await cache.SetAsync(
88+
"BaseKey",
89+
new CachedResponse()
90+
{
91+
Headers = new HeaderDictionary()
92+
{
93+
{ "MyHeader", "NewValue" }
94+
},
95+
Body = new SegmentReadStream(new List<byte[]>(0), 0)
96+
},
97+
TimeSpan.Zero);
98+
99+
Assert.True(await middleware.TryServeFromCacheAsync(context));
100+
Assert.Equal("NewValue", context.HttpContext.Response.Headers["MyHeader"]);
101+
Assert.Equal(1, cache.GetCount);
102+
TestUtils.AssertLoggedMessages(
103+
sink.Writes,
104+
LoggedMessage.CachedResponseServed);
105+
}
106+
78107
[Fact]
79108
public async Task TryServeFromCacheAsync_VaryByRuleFound_CachedResponseNotFound_Fails()
80109
{

0 commit comments

Comments
 (0)