asp.net-core.net-corecachinghttp-caching

ASP.NET Core - difference between Output caching and Response caching


ASP.NET Core 7 preview 6 just introduced Output caching which caches the endpoint output. However ASP.NET already has Response caching which seems to already provide the same feature.
What is the difference between the two and when should one be used and when should the other be used?


Solution

  • I was looking for answers and trying to understand the differences between both, and really took a huge amount of time to understand the differences between the two, and when (or not) to use each other.

    As of November 2022 .Net 7 has been released, but the documentation is not very clear about the differences between them. The documentation and all videos only talk about the OutputCache as a replacement for the ResponseCache. Also searching for OutputCache, it comes up with a lot of results from the old AspNet (Full framework) MVC 5.

    So let´s clarify the differences and how we could use each other.

    ResponseCache

    First, the ResponseCache can be divided in 2 parts, that work independently and are different concepts of how and where the information would be cached. Let´s catch them up:

    1. ResponseCacheAttribute: Basically it manipulates cache header like Vary, Cache-Control and others. It works telling the browsers or proxies to store (or not) the response content. This technique can reduce the number of requests done to the server, if used correctly.

    The ResponseCache attribute sets response caching headers. Clients and intermediate proxies should honor the headers for caching responses. under the HTTP 1.1 Caching specification

    1. Response Caching Middleware: Basically, it is used to make server-side caching based on headers defined by ResponseCacheAttribute. Depending on the Request Headers sent to the server, the response would never be cached on server side.

    Enables caching server responses based on HTTP cache headers. Implements the standard HTTP caching semantics. Caches based on HTTP cache headers like proxies do.

    Is typically not beneficial for UI apps such as Razor Pages because browsers generally set request headers that prevent caching. Output caching, which is available in ASP.NET Core 7.0 and later, benefits UI apps. With output caching, configuration decides what should be cached independently of HTTP headers.

    And at this point that OutputCache comes as a replacement for Response Caching Middleware.

    OutputCache (available in ASP.NET Core 7.0 and later)

    The OutputCache configuration decides what should be cached (server side) independently of HTTP headers. Also, it comes with a lot of new features like cache entry invalidation, storage medium extensibility and others.

    Conclusion

    To take the benefits from both worlds you can use:

    Both works independently. You can choose the one that fits best you application.