Follow us

Header Ads

Caching in Asp.Net Core

Caching in Asp.Net Core

Package

  • "Microsoft.Extensions.Caching.Memory" Version="6.0.1" 
  • "Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" 

Controllers[Home]

HomeController.cs

using Caching.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace Caching.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        private IMemoryCache MemoryCache;
        public HomeController(ILogger<HomeController> logger, IMemoryCache memoryCache)
        {
            _logger = logger;
            MemoryCache = memoryCache;
        }
        public IActionResult Index()
        {
            DateTime CurrentTime;
            bool value = MemoryCache.TryGetValue("CachedTime", out CurrentTime);
            if(!value)
            {
                CurrentTime = DateTime.Now;
                var cacheEntryOption = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(30));
                MemoryCache.Set("CachedTime", CurrentTime, cacheEntryOption);
            }
            return View(CurrentTime);
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}


Views[Folder]

Home[Folder]

Index.cshtml

@model DateTime?
@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>
<!--Current time change after referesh but cach time cannot change after referesh.But Cach time referesh after 30 seconds-->
<div>
    Current Time:
    @DateTime.Now.ToString();
</div>
<div>
    Cached Time:
    @Model.Value.ToString();
</div>

Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Caching
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            //add it for Caching
            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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}


Post a Comment

0 Comments