ASP.NET Core Utilizzo delle sessioni
Una volta configurato NCache come cache predefinita per ASP.NET Core Sessioni, è possibile eseguire tutti gli ASP.NET Core Operazioni specifiche della sessione senza alcuna modifica del codice. Tutte le sessioni verranno memorizzate nella cache in distribuito NCache.
L'esempio di codice seguente cerca la chiave di cache nella cache e, se viene trovata, restituisce la vista con il risultato. In caso contrario, aggiunge la chiave di cache alla voce di cache corrispondente e imposta la scadenza scorrevole della voce di cache su 30 minuti.
Per maggiori dettagli su IDistributedCache
metodi, dai un'occhiata la loro documentazione.
Utilizzo dell'ASP.NET Core Sessioni per una singola cache
Per utilizzare ASP.NET Core Aggiornamento delle sessioni HomeController.cs della tua domanda:
public class HomeController : Controller
{
private IDistributedCache _cache;
public HomeController(IDistributedCache Cache)
{
// Underlying cache is NCache
_cache = Cache;
}
public IActionResult CacheOperations()
{
// Cache entry is of DateTime type
DateTime cacheEntry;
string cacheKey = "MaxValue: " + DateTime.MaxValue;
// Look for cache key
object retrieveObj = _cache.Get(cacheKey);
// Check if key exists in cache
if (retrieveObj != null)
{
// Return view with result
}
else
{
// Key not in cache, so populate data in cache entry
cacheEntry = DateTime.MaxValue;
// Configure SlidingExpiration for item
var cacheEntryOptions = new DistributedCacheEntryOptions();
cacheEntryOptions.SlidingExpiration = TimeSpan.FromMinutes(30);
// Insert item in cache
_cache.Set(cacheKey, new byte[1024], cacheEntryOptions);
// Return view with cacheEntry
}
}
}
Utilizzo dell'ASP.NET Core Sessioni per più cache
Note:
Questa funzione è disponibile in NCache Enterprise solo.
public class HomeController : Controller
{
private IDistributedCacheFactory _cache;
public HomeController(IDistributedCacheFactory cacheFactory)
{
// Underlying cache is NCache
_cache = cacheFactory.GetDistributedCache("demoClusteredCache");
}
public IActionResult CacheOperations()
{
// Cache entry is of DateTime type
DateTime cacheEntry;
string cacheKey = "MaxValue: " + DateTime.MaxValue;
// Look for cache key
object retrieveObj = _cache.Get(cacheKey);
// Check if key exists in cache
if (retrieveObj != null)
{
// Return view with result
}
else
{
// Key not in cache, so populate data in cache entry
cacheEntry = DateTime.MaxValue;
// Configure SlidingExpiration for item
var cacheEntryOptions = new DistributedCacheEntryOptions();
cacheEntryOptions.SlidingExpiration = TimeSpan.FromMinutes(30);
// Insert item in cache
_cache.Set(cacheKey, new byte[1024], cacheEntryOptions);
// Return view with cacheEntry
}
}
}
Risorse addizionali
NCache fornisce un'applicazione di esempio per la memorizzazione nella cache della sessione GitHub.
Vedere anche
.NETTO: Alachisoft.NCache.Caching.Distribuito spazio dei nomi.