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.
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.
As @DOMZE said, you may consider using a custom middleware. Actually, response caching is already implemented as a middleware.
But as you want to add caching only to all MVC actions, the better way is to use MVC action filters. One of the benefits is that you may apply filter only to specific controller/action + you will have access to ActionExecutingContext
(controller instance/ action arguments )
public class ResponseCacheActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
// before the action executes
}
public void OnActionExecuted(ActionExecutedContext context)
{
// after the action executes
// add here a common Cache-Control and related headers to all responses
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With