Wednesday 4 January 2023

Sessions and Caching In ASP.NET Core

 How To Use Sessions In ASP.NET Core

1- We need to install the stable version of “Microsoft.AspNetCore.Session” from the NuGet Package Manager. Then only we can access the session state in ASP.NET Core.

2- Now, open the ”Startup.cs” to configure the services.  we need to add the session service to the container so that we can add the services in the “ConfigureServices” function.

public void ConfigureServices(IServiceCollection services)  
{
    services.AddDistributedMemoryCache();  
    services.AddSession(options => {  
        options.IdleTimeout = TimeSpan.FromMinutes(1); //Set Time  
    });  
    services.AddMvc();  
}

3- Configure the HTTP Request Pipeline

Now, in the same class, we add “app.UseSession()” inside the “Configure” function so that it gets called by the runtime.

app.UseSession();

Now we are ok to use session in our application. See the below code for session.

public class HomeController : Controller  
{  
    const string SessionName = "_Name";  
    const string SessionAge = "_Age";  
    public IActionResult Index()  
    {  
        HttpContext.Session.SetString(SessionName, "Jarvik");  
        HttpContext.Session.SetInt32(SessionAge, 24);  
        return View();  
    }  

    public IActionResult About()  
    {  
        ViewBag.Name = HttpContext.Session.GetString(SessionName);  
        ViewBag.Age = HttpContext.Session.GetInt32(SessionAge);  
        ViewData["Message"] = "Asp.Net Core !!!.";  

        return View();  
    }  
}

Cache in ASP.NET Core

ASP.NET Core supports several different caches. The simplest cache is based on the IMemoryCache. IMemoryCache represents a cache stored in the memory of the web server. Apps running on a server farm (multiple servers) should ensure sessions are sticky when using the in-memory cache. Sticky sessions ensure that requests from a client all go to the same server. 

Non-sticky sessions in a web farm require a distributed cache to avoid cache consistency problems. 

The in-memory cache can store any object. The distributed cache interface is limited to byte[]. The in-memory and distributed cache store cache items as key-value pairs.

Types of Caching in Dotnet Core: 

The lowest level of caching in ASP.NET Core that we are going to discuss is the caching of data using IMemoryCache and IDistributedCache. These interfaces are the standard, in-built mechanisms for caching data in .NET Core. All other techniques that we discuss later in the article rely on IMemoryCache or IDistributedCache internally.

IMemoryCache: IMemoryCache is very similar to the System.Runtime.Caching.MemoryCache cache from .NET 4.

You can register IMemoryCache in ConfigureServices using:

services.AddMemoryCache();

//services.AddDistributedMemoryCache();
//services.AddResponseCaching();

Implementing MemoryCache in Code.

public class BlahService
{
    private const string BlahCacheKey = "blah-cache-key";
    private readonly IMemoryCache _cache;

    public BlahService(IMemoryCache cache, IDatabase db)
    {
        _cache = cache;
    }
   
    public async Task<IEnumerable<Blah>> GetBlahs()
    {
        blahs = await _db.getAll<Blah>(...);
        _cache.Set(BlahCacheKey, blahs, ...);
        return blahs;
    }
}

When saving to IMemoryCache, MemoryCacheEntryOptions provides you with many ways to expire cache content. 

//absolute expiration using TimeSpan
_cache.Set("key", item, TimeSpan.FromDays(1));

//absolute expiration using DateTime
_cache.Set("key", item, new DateTime(2020, 1, 1));

//sliding expiration (evict if not accessed for 7 days)
_cache.Set("key", item, new MemoryCacheEntryOptions
{
    SlidingExpiration = TimeSpan.FromDays(7)
});

Learn more about Memory Cache https://learn.microsoft.com

IDistributedCache A distributed cache is a cache shared by multiple app servers, typically maintained as an
external service to the app servers that access it. A distributed cache can improve the performance
and scalability of an ASP.NET Core app, especially when the app is hosted by a cloud service
or a server farm.
A distributed cache has several advantages over other caching scenarios where cached data is
stored on individual app servers.
When cached data is distributed, the data:
  1. Is coherent (consistent) across requests to multiple servers.
  2. Survives server restarts and app deployments.
  3. Doesn't use local memory.
Distributed cache configuration is implementation specific. This article describes how to configure
SQL Server and Redis distributed caches. Third party implementations are also available, such as
NCache (NCache on GitHub). Regardless of which implementation is selected, the app interacts with
the cache using the IDistributedCache interface.

Learn More about distributed cache


0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives