Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a browser caching policy to all ASP.NET Core MVC pages

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.

like image 681
Edward Brey Avatar asked Feb 07 '17 18:02

Edward Brey


2 Answers

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.

like image 51
Tseng Avatar answered Nov 11 '22 07:11

Tseng


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
     }
}
like image 27
Set Avatar answered Nov 11 '22 05:11

Set