cachingasp.net-core-mvchttp-cachinghttpresponsecacheresponsecache

Saving the response cache to the server in Net 5


As in Net MVC, I want to save the response cache to the server (it's called outputcache), but there is no such feature in Net Core or Net 5. I couldn't find an alternative method. Thank you in advance.


Solution

  • You can use WebEssentials.AspNetCore.OutputCaching nuget to achieve your requirement.

    Follow the steps below:

    1.Add the middleware:

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    
        public IConfiguration Configuration { get; }
        public void ConfigureServices(IServiceCollection services)
        {
             services.AddOutputCaching();
             //other middleware...
        }
    
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseOutputCaching();
    
            //other middleware...
        }
    }
    

    2.Add OutputCache attribute to the action:

    [OutputCache(Duration = 600)]
    public IActionResult Index()
    { ... }
    

    A sample code for testing:

    Controller:

    [OutputCache(Duration = 600)]
    public IActionResult Index()
    {        
        return View(DateTime.Now);
    }
    

    View:

    @model DateTime
    
    Time of request: @Model.ToString()
    

    Try requesting the page and notice that the date and time remains the same, even when reloading the page, until the cache has expired.

    OutputCache contains not least Duration option, but also other options, such as VaryByHeader, VaryByParam and so on...

    More details you can refer to the github repo for WebEssentials.AspNetCore.OutputCaching