Saturday, July 22, 2023

ASP.NET Core Razor Pages In-Memory Cache Example


Project
  • Open the Visual Studio. 
  • Create web project using ASP.NET Core Empty template.
  • Project name: RPExercises
  • Solution name: RPExercises
  • .NET Core version: 5.0
  • Add the AddRazorPages() into the IServiceCollection in Startup class.
  • Add the AddMemoryCache() into the IServiceCollection in Startup class.
  • Use MapRazorPages() as terminal middleware in Startup class.
Look at the below updated code in Startup class.
Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace CascadingDropdownsRP
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages(); 
            services.AddMemoryCache();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}
  • Add a New Folder and rename it Pages.
  • Add a Razor Page in Pages folder and name it Index. Two files are generated which are Index.cshtml and Index.cshtml.cs
Next step. Update the Index.cshtml to create a list of tasks in the table.
Index.cshtml

@page "{handler?}"
@model RPExercises.Pages.IndexModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

<h1>All about in-memory cache</h1>
<ul>
    <li>When this page is loaded, its current time of loading page is cached in memory</li>
    <li>Click the anchor link to get the time when it was loaded.</li>
</ul>
<hr/>
<a asp-page="Index" asp-page-handler="CachedTime">Click me</a>
 <br/>
 <br/>
 Cached at: 
@ViewData["timestamp"]
Index.cshtml.cs 

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Caching.Memory;
using System;

namespace RPExercises.Pages
{
    public class IndexModel : PageModel
    {
        private readonly IMemoryCache memoryCache;

        public IndexModel(IMemoryCache memoryCache)
        {
            this.memoryCache = memoryCache;
        }
        public void OnGet()
        {
            // key,value pairs
            memoryCache.Set<string>("currentTime", DateTime.Now.ToString());
        }
        public void OnGetCachedTime()
        {
            // key,value pairs
            ViewData["timestamp"]= memoryCache.Get<string>("currentTime");
        }

    }
}
Run the application. Wait for some time and click the Click me link. 

Some Important Terms

An absolute expiration means a cached item will be removed from cache memory on a fixed date and time, no matter the item is used or not. Sliding expiration means a cached item will be removed from cache memory when the item is not used for a fixed span of time.

Following are important methods and properties of IMemoryCache object.

To use the options in memory cache, MemoryCacheEntryOptions class is used. An example is given below by updating the previous code. The absolute expiration is set 1 day later from the point of time caching was done. No matter cache data is used or not, it will be removed from cache memory after 1 day. The sliding expiration is set 20 minutes. It implies that if the cache data is not used for more than 20 minutes then data will be removed form the cache memory.


public void OnGet()
        {
            // options
            MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
            options.AbsoluteExpiration = DateTime.Now.AddDays(1);
            options.SlidingExpiration = TimeSpan.FromMinutes(20);
            // key,value pairs
            memoryCache.Set("currentTime", DateTime.Now.ToString(), options);
        }

No comments:

Post a Comment

Hot Topics