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)
});
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:
- Is coherent (consistent) across requests to multiple servers.
- Survives server restarts and app deployments.
- 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
the cache using the IDistributedCache interface.
0 comments:
Post a Comment