ASP.NET Core Caching in Practice

ASP.NET Core-Caching-in-Practice

Cache-Control HTTP Header

The Cache-Control HTTP header can be used to set how long your resource can be cached for. However, the problem with this HTTP header is that you need to be able to predict the future and know before hand when the cache will become invalid. For some use cases, like writing an API where someone could change the resource at any time that's just not feasible.

I recommend you read the response caching middleware documentation, it's not necessary as I do a quick overview next but the knowledge below builds upon it. The simple way to set the cache control header is directly on the action method like so:

[HttpGet, ResponseCache(Duration = 3600, Location = ResponseCacheLocation.Any)]
public IActionResult GetCats()

Adding the ResponseCache attribute just adds the Cache-Control HTTP header but does not actually cache the response on the server. To do that you also need to add the response caching middleware like so:

public void Configure(IApplicationBuilder application) =>
    application.UseResponseCaching().UseMvc();

Instead of hard coding all of your cache settings in the ResponseCache attribute, it's possible to store them in the appsettings.json configuration file. To do so, you need to use a feature called cache profiles which look like this:

[HttpGet, ResponseCache(CacheProfile="Cache1Hour")]
public IActionResult GetCats()

public class Startup
{    
    private readonly IConfiguration configuration;
    
    public Startup() => this.configuration = configuration;

    public void ConfigureServices(IServiceCollection services) =>
        services
            .Configure<Dictionary<string, CacheProfile>>(configuration.GetSection("CacheProfiles"))
            .AddMvc(options =>
            {
                // Read cache profiles from appsettings.json configuration file
                var cacheProfiles = this.configuration.GetSection<Dictionary<string, CacheProfile>>();
                foreach (var keyValuePair in cacheProfiles)
                {
                    options.CacheProfiles.Add(keyValuePair);
                }
            });
            
    // Omitted
}
{
  "CacheProfiles": {
    "Cache1Hour": {
      "Duration": 3600,
     "Location": "Any"
    }
  },
  // Omitted...
}

Now all your caching can be configured from a single configuration file.

Cache-Control Immutable Directive

Cache-Control also has a new draft directive called immutable. When you add this to the HTTP header value, you are basically telling the client that this resource never changes even if it has expired. You might be asking, why do we need this? Well, it turns out that when you refresh a page in a browser, it goes off to the server and checks to see if the resource has expired or not.

Cache-Control: max-age=365000000, immutable

It turns out that you get a massive reduction in requests to your server by implementing this directive. Read more about it in these links:

This directive has not yet been implemented in ASP.NET Core but I've raised an issue on GitHub here and there is also another issue here to add the immutable directive to the static files middleware. If you really wanted to, it's really easy to add this directive today, as you just need to append the word immutable onto the end of your Cache-Control HTTP header.

A word of warning! You need to make sure that your resource really never changes. You can do this in Razor by using the asp-append-version attribute on your script tags:

<script src="~/site.js" asp-append-version="true"></script>

This will append a query string to the link to site.js which will contain a hash of the contents of the file. Each time the file changes, the hash is changed and thus you can safely mark the resource as immutable.

E-Tags

E-tags are typically generated in three ways (Read the link to understand what they are):

  1. Hashing the HTTP response body - You'd want to use a very fast and collision resistant hash function like MD5 (MD5 is broken security wise and you should never use it but it's ok to use it for caching). Unfortunately, this method is slow because you have to load the entire response body into memory (which is not the default in ASP.NET Core which streams it straight to the client for better performance) to hash it. If you're still interested in implementing this E-Tag's using this method Mads Kristensen wrote a nice blog post showing how it can be done.
  2. Last modification timestamp - The E-Tag can literally be the time the object was last modified which you can store in your database (I usually store created and modified timestamps for anything I store in a database anyway). This solves the performance problem above but now what is the difference between doing this and using the Last Modified HTTP header?
  3. Revision Number - This could be some kind of integer stored in the database which gets incremented each time the data is modified. I don't see any advantage of doing this over using the last modification timestamp above, unless you have a naturally occurring revision number in your data that you could use.

One additional thing you need to be careful of is the Accept, Accept-Encoding and Accept-Language HTTP headers. Any time you send a different response based on these HTTP headers, your E-Tag needs to be different e.g. a JSON non-gzip'ed response in Mandarin needs to have a different E-Tag to an XML gzip'ed response in Urdu.

For option one, this can be achieved by calculating the hash after the response body has gone through GZIP compression. For the second and third options, you would need to append the value of the Accept HTTP headers to the last modified date or revision number and then hash all of that.

Last-Modified & If-Modified-Since

I'm assuming you already know about the Last-Modified and If-Modified-Since HTTP headers. If not, go ahead and read the links. Below is an example controller and action method that returns a list of cats.

[Route("[controller]")]
public class CatsController : ControllerBase
{
    private readonly ICatRepository catRepository;
    private readonly ICatMapper catMapper;

    public CatsController(
        ICatRepository catRepository,
        ICatMapper catMapper)
    {
        this.catRepository = catRepository;
        this.catMapper = catMapper;
    }

    [HttpGet("")]
    public async Task<IActionResult> GetCats(CancellationToken cancellationToken)
    {
        var cats = await this.catRepository.GetAll(cancellationToken);
        var lastModified = cats.Count == 0 ? 
            (DateTimeOffset?)null : 
            cats.Max(x => x.ModifiedTimestamp);

        this.Response.GetTypedHeaders().LastModified = lastModified;

        var requestHeaders = this.Request.GetTypedHeaders();
        if (requestHeaders.IfModifiedSince.HasValue &&
            requestHeaders.IfModifiedSince.Value >= lastModified)
        {
            return this.StatusCode(StatusCodes.Status304NotModified);
        }

        var catViewModels = this.catMapper.MapList(cats);
        return this.Ok(catViewModels);
    }
}

All of our cats have a ModifiedTimestamp, so we know when they were last changed. There are four scenarios that this action method handles:

  1. Our repository does not contain any cats, so just always return an empty list.
  2. No Last-Modified HTTP header exists in the request, so we just return all cats.
  3. Last-Modified HTTP header exists and cats have been modified since that date, so return all cats.
  4. Last-Modified HTTP header exists but no cats have been modified since that date, so return a 304 Not Modified response.

In all cases, except when we have no cats at all, we set the Last-Modified date to the latest date than any cat has been modified.

Conclusions

Which caching HTTP headers you pick, depends on your data but at a minimum, I would add E-Tag's or Last-Modified. Add Cache-Control where possible, usually for static assets.

Web Mentions

What's this?

0 Replies

GitHub Comments

RehanSaeed

Robin Robin commented on 2017-10-26 15:48:26

hmmm, I'm doing similar things by adding the following to my Configure method in startup.cs:

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =
    {
        const int durationInSeconds = 60 * 60 * 24 * 1; //one day!
        ctx.Context.Response.Headers.Add("cache-control", new[] { "public,max-age=" + durationInSeconds });
        ctx.Context.Response.Headers.Add("Expires", new[] { DateTime.UtcNow.AddSeconds(durationInSeconds).ToString("R") }); // Format RFC1123
    }
});

I'm only concerned with caching "big" things like images etc (which is why its for static files).

RehanSaeed
(edited )

Shahzad Hassan Shahzad Hassan commented on 2017-10-26 16:08:14

Thanks for sharing. Yet again, a very nice blog indeed. I have a question for you.

I know that Response Caching cannot be used if Authorization header is present in the request. I have a scenario where multiple API subscribers need to pass in a Bearer token in the Authorization header so the request can be authenticated/authorized. However, the response of a REST API call is exactly the same regardless of who is calling, as far as they are authenticated.

How would you approach to solve this particular problem? Would you recommend implementing a custom caching layer using ResourceFilters or something as they will be second in a row after the AuthorizeFilters? What are your thoughts on it?

Thanks

RehanSaeed

Muhammad Rehan Saeed Muhammad Rehan Saeed commented on 2017-11-13 09:03:31

hmmm, I'm doing similar things by adding the following to my Configure method in startup.cs:

app.UseStaticFiles(new StaticFileOptions
{
    OnPrepareResponse = ctx =
    {
        const int durationInSeconds = 60 * 60 * 24 * 1; //one day!
        ctx.Context.Response.Headers.Add("cache-control", new[] { "public,max-age=" + durationInSeconds });
        ctx.Context.Response.Headers.Add("Expires", new[] { DateTime.UtcNow.AddSeconds(durationInSeconds).ToString("R") }); // Format RFC1123
    }
});

I'm only concerned with caching "big" things like images etc (which is why its for static files).

Looks reasonable. Setting Cache-Control, Expires and Pragma HTTP headers is complicated, which is why I use the helper method.

RehanSaeed
(edited )

Muhammad Rehan Saeed Muhammad Rehan Saeed commented on 2017-11-13 09:11:13

Thanks for sharing. Yet again, a very nice blog indeed. I have a question for you.

I know that Response Caching cannot be used if Authorization header is present in the request. I have a scenario where multiple API subscribers need to pass in a Bearer token in the Authorization header so the request can be authenticated/authorized. However, the response of a REST API call is exactly the same regardless of who is calling, as far as they are authenticated.

How would you approach to solve this particular problem? Would you recommend implementing a custom caching layer using ResourceFilters or something as they will be second in a row after the AuthorizeFilters? What are your thoughts on it?

Thanks

This GitHub issue in the aspnet/ResponseCache repository deals with caching being turned off when the Authorization HTTP header is present.

In my opinion, the best way to go might be to override or replace the logic in the ResponseCache middleware where caching is turned off based on the Authorization HTTP header.

RehanSaeed

Shahzad Hassan Shahzad Hassan commented on 2017-11-23 08:26:51

This GitHub issue in the aspnet/ResponseCache repository deals with caching being turned off when the Authorization HTTP header is present.

In my opinion, the best way to go might be to override or replace the logic in the ResponseCache middleware where caching is turned off based on the Authorization HTTP header.

Ok, Thanks. Makes sense, l will have a look.

RehanSaeed

John John commented on 2018-06-29 08:16:29

Nice post. The way you controller works it's kind confusing me. You always hit the db to fetch all the data anyway.. so no much optimization there. Or maybe was just a silly example? Thanks!

RehanSaeed

Muhammad Rehan Saeed Muhammad Rehan Saeed commented on 2018-06-29 09:23:56

Nice post. The way you controller works it's kind confusing me. You always hit the db to fetch all the data anyway.. so no much optimization there. Or maybe was just a silly example? Thanks!

Yes, that's a good point. The code I've shown optimises what gets sent over the wire but not the database calls. If you wanted to optimise the database call, you could start with a query that returns the count for the number of items and the latest modified timestamp and use that to figure out if you need to do another query to get all of the data or return a 304 not modified response.

RehanSaeed
(edited )

Noah Noah commented on 2018-11-16 07:43:47

Great article about caching. While, I have read HTTP-based cache mechanism here, and I want to know does HTTP-based cache make sense for an Web API application? Back to your example for Last-Modified & If-Modified-Since, is it reasonable for an API client receiving 304 response? Could you provide some advice and best practices about implementing HTTP-based cache for a Web API application? Thanks.

RehanSaeed

Muhammad Rehan Saeed Muhammad Rehan Saeed commented on 2018-11-16 09:06:25

Great article about caching. While, I have read HTTP-based cache mechanism here, and I want to know does HTTP-based cache make sense for an Web API application? Back to your example for Last-Modified & If-Modified-Since, is it reasonable for an API client receiving 304 response? Could you provide some advice and best practices about implementing HTTP-based cache for a Web API application? Thanks.

It does make sense sometimes. If the resource you are getting has a last modified date that you store in the database, you can take that and turn it into Last-Modified & If-Modified-Since HTTP headers. If your client is a web browser, then it will respect the header. If the client is custom code such as C#'s HttpClient, then you will need to write some extra code to respect the HTTP headers and cache responses.

RehanSaeed

Muhammad Rehan Saeed Muhammad Rehan Saeed commented on 2018-12-01 10:59:58

Great article about caching. While, I have read HTTP-based cache mechanism here, and I want to know does HTTP-based cache make sense for an Web API application? Back to your example for Last-Modified & If-Modified-Since, is it reasonable for an API client receiving 304 response? Could you provide some advice and best practices about implementing HTTP-based cache for a Web API application? Thanks.

I can make sense for an API. You just need to know when the resource was last changed. Also, the client has to support caching headers and store resources in some way that makes sense.

RehanSaeed

Abhi Abhi commented on 2019-04-12 12:37:50

Hi,

Thank you for good article,

I am getting error on the line

var cacheProfiles = this.configuration.GetSection<Dictionary<string, CacheProfile>>();

GetSection not supporting..

.netcore 2.1 framework

RehanSaeed

Al Stevens Al Stevens commented on 2019-12-16 17:49:31

Hi,

Thank you for good article,

I am getting error on the line

var cacheProfiles = this.configuration.GetSection<Dictionary<string, CacheProfile>>();

GetSection not supporting..

.netcore 2.1 framework

Abhi,

I hit the same thing too, you need to change it to the following:

var cacheProfiles = this.configuration.GetSection("CacheProfiles").Get<Dictionary<string, CacheProfile>>();

Hope that helps.

xhafan

Thanks the article helped me

terryaney

I'm trying to do the same thing you described in the 'Last-Modified & If-Modified-Since' section. However, after the initial call to the controller, Chrome (and I tested FF too) doesn't even call back to my controller. I simply returns like this:

image

It says (disk cache). I haven't done any 'configuration setup' in Startup. I simply implemented code for checking if-modified-since against our database timestamp. Do I need code in Startup to make this work?

RehanSaeed

@terryaney If you've implemented the headers you mention correctly and the header is telling the browser that a resource has not been modified since it last made a request to the resource then the browser will cache that resource. This is why you get a 'disk cache' in the browsers network tab. Is that not what you want?

terryaney

I'm just saying that it doesn't even post back to my action so that I can check 'if-modified-since' against my database. The browser just caches it itself. So when I update the resource in our database, the new version is never returned because it doesn't hit my code.

protected async Task<IActionResult> CachedOrModifiedAsync( CacheDownloadInfo cacheDownloadInfo, IDbConnectionFactory dbConnectionFactory )
{
	var lastModifiedDate = cacheDownloadInfo.LastModifiedDate.Value.ToUniversalTime();

	// https://rehansaeed.com/asp-net-core-caching-in-practice/#last-modified--if-modified-since
	// https://www.geekytidbits.com/efficient-caching-dynamic-resources-asp-net-304-not-modified/
	var requestHeaders = HttpContext.Request.GetTypedHeaders();
	if ( !requestHeaders.IfModifiedSince.HasValue )
	{
		// Set Last Modified time
		HttpContext.Response.GetTypedHeaders().LastModified = lastModifiedDate;
	}
	else
	{
		// HTTP does not provide milliseconds, so remove it from the comparison
		if ( lastModifiedDate.AddMilliseconds( -lastModifiedDate.Millisecond ) == requestHeaders.IfModifiedSince.Value )
		{
			return NotModified();
		}
	}

	var bds = new SqlBinaryDataStream<Guid>( dbConnectionFactory.GetDataLockerConnectionString(), "Cache", "UID", "Content", cacheDownloadInfo.Token.Value );
	return new FileStreamResult( await bds.ContentIsCompressedAsync ? new GZipStream( bds, CompressionMode.Decompress ) : bds, cacheDownloadInfo.ContentType );
}
RehanSaeed

Perhaps consider creating a small sample app and posting the question on StackOverflow to get some eyes on it (I'll also take a look).

terryaney
(edited )

FYI, I updated my stack overflow answer here. But to make this work with Swagger (maybe other clients as well), I had to put the following:

responseHeaders.CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue
{
	Public = true,
	MustRevalidate = true,
	MaxAge = new TimeSpan( 0, 0, 0 ),
};
responseHeaders.Expires = DateTime.UtcNow;