Server-side caching middleware for ASP.NET 2.0
Start by registering the service it in Startup.cs
like so:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddOutputCaching();
}
...and then register the middleware just before the call to app.UseMvc(...)
like so:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseOutputCaching();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
There are various ways to use and customize the output caching. Here are some examples.
Use the OutputCache
attribute on a controller action:
[OutputCache(Duration = 600, VaryByParam = "id")]
public IActionResult Product()
{
return View();
}
Using the EnableOutputCaching
extension method on the HttpContext
object in MVC, WebAPI or Razor Pages:
public IActionResult About()
{
HttpContext.EnableOutputCaching(TimeSpan.FromMinutes(1));
return View();
}
Set up cache profiles to reuse the same settings.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddOutputCaching(options =>
{
options.Profiles["default"] = new OutputCacheProfile
{
Duration = 600
};
});
}
Then use the profile from an action filter:
[OutputCache(Profile = "default")]
public IActionResult Index()
{
return View();
}