Overwrite headers when serving response from cache #101

This commit is contained in:
John Luo 2017-02-03 14:25:59 -08:00
parent 267f5134c8
commit d43f05189a
2 changed files with 31 additions and 2 deletions

View File

@ -152,7 +152,7 @@ namespace Microsoft.AspNetCore.ResponseCaching
response.StatusCode = context.CachedResponse.StatusCode; response.StatusCode = context.CachedResponse.StatusCode;
foreach (var header in context.CachedResponse.Headers) foreach (var header in context.CachedResponse.Headers)
{ {
response.Headers.Add(header); response.Headers[header.Key] = header.Value;
} }
// Note: int64 division truncates result and errors may be up to 1 second. This reduction in // Note: int64 division truncates result and errors may be up to 1 second. This reduction in
@ -287,7 +287,7 @@ namespace Microsoft.AspNetCore.ResponseCaching
{ {
if (!string.Equals(header.Key, HeaderNames.Age, StringComparison.OrdinalIgnoreCase)) if (!string.Equals(header.Key, HeaderNames.Age, StringComparison.OrdinalIgnoreCase))
{ {
context.CachedResponse.Headers.Add(header); context.CachedResponse.Headers[header.Key] = header.Value;
} }
} }
} }

View File

@ -75,6 +75,35 @@ namespace Microsoft.AspNetCore.ResponseCaching.Tests
LoggedMessage.CachedResponseServed); LoggedMessage.CachedResponseServed);
} }
[Fact]
public async Task TryServeFromCacheAsync_CachedResponseFound_OverwritesExistingHeaders()
{
var cache = new TestResponseCache();
var sink = new TestSink();
var middleware = TestUtils.CreateTestMiddleware(testSink: sink, cache: cache, keyProvider: new TestResponseCachingKeyProvider("BaseKey"));
var context = TestUtils.CreateTestContext();
context.HttpContext.Response.Headers["MyHeader"] = "OldValue";
await cache.SetAsync(
"BaseKey",
new CachedResponse()
{
Headers = new HeaderDictionary()
{
{ "MyHeader", "NewValue" }
},
Body = new SegmentReadStream(new List<byte[]>(0), 0)
},
TimeSpan.Zero);
Assert.True(await middleware.TryServeFromCacheAsync(context));
Assert.Equal("NewValue", context.HttpContext.Response.Headers["MyHeader"]);
Assert.Equal(1, cache.GetCount);
TestUtils.AssertLoggedMessages(
sink.Writes,
LoggedMessage.CachedResponseServed);
}
[Fact] [Fact]
public async Task TryServeFromCacheAsync_VaryByRuleFound_CachedResponseNotFound_Fails() public async Task TryServeFromCacheAsync_VaryByRuleFound_CachedResponseNotFound_Fails()
{ {