Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching full response on the server

Here's a very small sample Razor Page:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

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

//model
public class IndexModel : PageModel
{
    private readonly ILogger<IndexModel> _logger;

    public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;
    }

    public void OnGet()
    {

    }
}

If I use this code, the time will update every 30 seconds which is what is intended:

<cache expires-after="TimeSpan.FromSeconds(30)">
    <h1>
        @DateTime.Now.ToString()
    </h1>
</cache>

However, adding the ResponseCache attribute to the model doesn't do this:

[ResponseCache(Duration = 30)]
public class IndexModel : PageModel

After doing some research it seems like the attribute only sends the appropriate headers to the client, asking it to cache the content. How can I store the entire response in memory so when the user asks for the specific page, the server just sends the cached response and eliminate the process of computing the result again?

Also, with the <cache> tag helper, I couldn't find a way to invalidate the cached entry. So one scenario for me would be to cache every single page in memory for 30 days and if I change something on the admin panel, I would then invalidate the cache for that specific item so the next request would produce the fresh result. I used to do this on Asp.Net MVC 3+ but couldn't find any method to achieve the same result in Asp.Net Core 3.1

like image 466
Alireza Noori Avatar asked May 09 '20 15:05

Alireza Noori


1 Answers

From your question it seems you might need to roll out your own version

How can I store the entire response in memory so when the user asks for the specific page, the server just sends the cached response and eliminate the process of computing the result again?

See the source of https://github.com/dotnet/aspnetcore/blob/master/src/Mvc/Mvc.Core/src/ResponseCacheAttribute.cs

And

https://github.com/aspnet/Mvc/blob/d8c6c4ab34e1368c1b071a01fcdcb9e8cc12e110/src/Microsoft.AspNetCore.Mvc.Core/Internal/ResponseCacheFilter.cs

It seems that it sets headers only.

You may implement your own version of caching like this one

https://www.devtrends.co.uk/blog/custom-response-caching-in-asp.net-core-with-cache-invalidation

See CachedPage class in above example.

like image 118
Ajay Kelkar Avatar answered Nov 15 '22 21:11

Ajay Kelkar