Response caching and output caching do not cache headers modified in OnStarting handler
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 6h
- Merged PRs (30d)
- 290
Description
### Is there an existing issue for this?
- [X] I have searched the existing issues
### Describe the bug
Response caching does not cache headers modified in the OnStarting delegate in middleware loaded after responsecaching middleware.
``` c#
context.Response.OnStarting(CheckIfHeaderNeeded, context);
private Task CheckIfHeaderNeeded(object state)
{
var context = (HttpContext)state;
context.Response.Headers.Remove("removeme");
return Task.CompletedTask;
}
```
revmoveme header will only be removed on the initial request
### Expected Behavior
Response caching should cache the actual final headers sent to the client. It cannot cache only headers created before the await(next) in middleware.
This will also fix #23218 if I understand the issue correctly.
@Tratcher mentioned one possible fix is
> One fix would be for the caching middleware to shim OnStarting and run those callbacks before it captured the headers. (Complex)
That seems to be the correct behavior
### Steps To Reproduce
https://github.com/lawrencek76/header-caching-issue
### Exceptions (if any)
_No response_
### .NET Version
6.0.101
### Anything else?
Initially ran into this trying to cache security headers with a nonce in another middleware.
https://github.com/andrewlock/NetEscapades.AspNetCore.SecurityHeaders/issues/117
After attempting to make a pr to fix this in the other middleware I realized there is really no way I can find to really do this correctly outside of the caching middleware itself.
https://github.com/andrewlock/NetEscapades.AspNetCore.SecurityHeaders/pull/118
Contributor guide
Assessment
This issue has not been assessed yet.