Response Caching in ASP.Net Core

Response Caching helps in improving performance of web server by caching relevant content based on certain criteria. Response caching is available in all versions of ASP.Net. In ASP.Net Core, there is a new Response Caching Middleware through which we can configure the caching options in Startup class. In this tutorial, we are going to see how to implement Response Caching middleware.

NOTE: Updated this tutorial on 2/27/2017 with MSBuild based Dotnet SDK.

Create an ASP.Net Core Application using VS 2017. I am using following version of Dotnet SDK which is based on MSBuild/CSProj (remember that previous versions of ASP.Net Core are based on Project.json/XProj.).

image

Lets get started by adding following package dependency.

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
  </PropertyGroup>
  <PropertyGroup>
    <PackageTargetFallback>$(PackageTargetFallback);portable-net45+win8+wp8+wpa81;</PackageTargetFallback>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.ResponseCaching" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.ResponseCompression" Version="1.0.0-preview1-final" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.0" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.0" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0-msbuild3-final" />
  </ItemGroup>
</Project>

Now configure Caching service in Startup class as shown below.

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddResponseCaching();
    services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseResponseCaching();
    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Lets include ResponseCache attribute on Index action of Home controller as shown below.

public class HomeController : Controller
{
    [ResponseCache(VaryByQueryKeys = new string[] { "test" }, Duration = 30)]
    public IActionResult Index()
    {
        return View();
    }
}

As shown above, we have configured Index action to be cached for different “test” query string values for duration 30 seconds.

To test this functionality, lets add DateTime string to Index view.

<div>@DateTime.Now.ToString()</div>

Lets run the application with /?test=sample, when we navigate to Index action with same query string value, then response will be sent from cache. Once duration is lapsed, cache will be expired and the subsequent response will be cached again and used for subsequent requests over the duration.

image

When we navigate to this action with any other query string value (for example sam as shown below), we get a new version generated and stored in cache.

image

ResponseCache can also be configured for:

  1. Duration and Location (Any or Client).
  2. no-store, no-cache using NoStore and Location.None.
  3. Vary by HTTP Header.

That’s it for now, Happy Coding and Stay Tuned!!!

You may also like...