3
votes

Can't seem to get it working. Really simple scenario...

<cache expires-after="@TimeSpan.FromMinutes(10)">
    @DateTime.Now
</cache>   

Running this in VS2017 in IISExpress (same behaviour in IIS 10 too btw) and hitting refresh in the browser (Chrome) just gives me the current time? I'm using .Net Core 2.1. I'm trying it in a partial and a view component and it just doesn't cache.

I'm not sure what I'm doing wrong.

For the record, I've added..

services.AddMemoryCache();

to the Startup ConfigureServices method (although according to the documentation (https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/cache-tag-helper?view=aspnetcore-2.1), I shouldn't even need to do this as it is added automatically - it says so right at the bottom).

This is also using Razor pages

2

2 Answers

4
votes

The problem might be that you haven't added the tag helpers. As a troubleshooting step, add the tag helpers to the view that has the <cache> element.

_SomePartial.cshtml

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<cache expires-after="@TimeSpan.FromMinutes(10)">
    @DateTime.Now
</cache>

If that solves the problem, you will probably want to make the tag helpers available to an entire directory instead of just to one file. Do that by moving the addTagHelper directive to a _ViewImports.cshtml file.

0
votes

There might be another possibility that makes cache tag helper not working.

I also had the same problem even though I'd added Microsoft tag helpers properly, my mistake was that I used DateTime.Now for expires-on attribute. see below

<cache expires-on="DateTime.Now.AddDays(1)"> @DateTime.Now </cache>

now date time DateTime.Now should not be used for cachetag helper because every time that the page is refreshed the expires-on value will be changed and cause the framework re-add the entry to cache with the new expires-on.

I changed expires-on="DateTime.Now.AddDays(1)" to expires-after="@TimeSpan.FromMinutes(43200)" and it worked.