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

Commit c4b3c4e

Browse files
committed
Overwrite headers when serving response from cache #101
1 parent 4e48475 commit c4b3c4e

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
@@ -133,7 +133,7 @@ internal async Task<bool> TryServeCachedResponseAsync(ResponseCachingContext con
133133
response.StatusCode = context.CachedResponse.StatusCode;
134134
foreach (var header in context.CachedResponse.Headers)
135135
{
136-
response.Headers.Add(header);
136+
response.Headers[header.Key] = header.Value;
137137
}
138138

139139
response.Headers[HeaderNames.Age] = context.CachedEntryAge.Value.TotalSeconds.ToString("F0", CultureInfo.InvariantCulture);
@@ -262,7 +262,7 @@ internal async Task FinalizeCacheHeadersAsync(ResponseCachingContext context)
262262
{
263263
if (!string.Equals(header.Key, HeaderNames.Age, StringComparison.OrdinalIgnoreCase))
264264
{
265-
context.CachedResponse.Headers.Add(header);
265+
context.CachedResponse.Headers[header.Key] = header.Value;
266266
}
267267
}
268268
}

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

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

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

0 commit comments

Comments
 (0)