Asp.net-core – Apply a browser caching policy to all ASP.NET Core MVC pages

asp.net-corebrowser-cachecache-control

I'd like to tell ASP.NET Core to add a common Cache-Control and related headers to all responses served by MVC controllers, both HTML pages and Web API responses. I don't want the policy to apply to cache static files; those I want to be cached.

In particular case, I want to disable caching, the equivalent of applying this attribute to all controllers:

[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]

I could made a base controller with this attribute and derive all other controllers from it. I was wondering if there is a configuration-based approach that avoids the need for such a base controller.

Best Answer

You can do it w/o middleware just by adding

services.AddMvc(options => {
    options.Filters.Add(new ResponseCacheAttribute() { NoStore = true, Location = ResponseCacheLocation.None });
})

in your ConfigureServices method. Works with any Attribute (i.e AuthorizeAttribute), which can be instantiated and will be applied to all controllers and actions. Also no need for a base class.

Related Topic