Search code examples
c#asp.netasp.net-corecachingasp.net-core-3.1

how can cache "NotFound" page in asp .net core


I have a custom NotFound page in my project that every false URL redirect to it by this code:

In startup.cs:

app.UseStatusCodePagesWithRedirects("/not-found");

I want to serve this static page by a cache policy. how can I do it?


Solution

  • You can first install this nuget package:

    WebEssentials.AspNetCore.OutputCaching

    And then add these code in startup.cs:

    services.AddOutputCaching(); //ConfigureServices()
    

    and

    app.UseOutputCaching();  //Configure()
    

    At last, add OutputCache attribute to your notfound() action, then it's output will be cached:

    [OutputCache(Duration = 6000)] //cache 6000 seconds
        public IActionResult notfound()
        {
            return View(DateTime.Now);
        }
    

    Result:

    enter image description here