• Facebook
  • Twitter
  • Youtube
  • LinedIn
  • RSS
  • Docs
  • Comparisons
  • Blogs
  • Download
  • Contact Us
Download
Show / Hide Table of Contents

ASP.NET Core Sessions Usage

NCache provides integration with ASP.NET Core Sessions through the implementation of the common IDistributedCache interface. Using NCache as a distributed session store is possible without any changes to existing code. Storing the session state in a distributed NCache cluster ensures that sessions are persisted, scalable, and highly available in a web farm.

For more details on IDistributedCache methods, have a look at their documentation.

Prerequisites

Before using the ASP.NET Core Sessions with NCache, ensure that the following prerequisites are fulfilled:

  • .NET
  • Install the following NuGet packages in your application based on your NCache edition:
    • Enterprise: AspNetCore.Session.NCache
    • OpenSource: AspNetCore.Session.NCache.Opensource
  • To utilize the extension, include the following namespaces in your application:
    • Alachisoft.NCache.Web.SessionState
  • The cache must be running.
  • For API details, refer to: AddNCacheSession, UseNCacheSession.
  • Make sure that the data being added is serializable.

Using ASP.NET Core Sessions for a Single Cache

The following code sample looks for the cache key, if it is found, it returns the view with the result. If not, it adds the cache key with its corresponding cache entry and sets the Sliding Expiration of the cache entry to 30 minutes. To use ASP.NET Core Sessions, update HomeController.cs of your application as follows:

// Constructor injection for the IDistributedCache interface

public class HomeController : Controller
{
    private IDistributedCache _cache;

    public HomeController(IDistributedCache Cache)
    {
        // NCache is the underlying distributed provider
        _cache = Cache;
    }

    public IActionResult CacheOperations()
    {
        try
        {
            DateTime cacheEntry;
            string cacheKey = "MaxValue: " + DateTime.MaxValue;

            object retrieveObj = _cache.Get(cacheKey);

            if (retrieveObj != null)
            {
                // Return view with result
                return View();
            }
            else
            {
                cacheEntry = DateTime.MaxValue;

                var cacheEntryOptions = new DistributedCacheEntryOptions
                {
                    SlidingExpiration = TimeSpan.FromMinutes(30)
                };

                _cache.Set(cacheKey, new byte[1024], cacheEntryOptions);

                return View(cacheEntry);
            }
        }
        catch (Exception ex)
        {
            // Handle error (log, fallback, etc.)
            // Example: return fallback view or error page
            return StatusCode(500, $"Cache error: {ex.Message}");
        }
    }
}
Note

To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.

Using ASP.NET Core Sessions For Multiple Caches

To utilize multiple caches with ASP.NET Core Sessions, modify your HomeController.cs to use IDistributedCacheFactory, enabling dynamic cache selection for session management based on specific cache configurations.

public class HomeController : Controller
{
    private IDistributedCacheFactory _cache;

    public HomeController(IDistributedCacheFactory cacheFactory)
    {
        // Underlying cache is NCache
        _cache = cacheFactory.GetDistributedCache("demoClusteredCache");
    }

    public IActionResult CacheOperations()
    {
        try
        {
            DateTime cacheEntry;
            string cacheKey = "MaxValue: " + DateTime.MaxValue;

            object retrieveObj = _cache.Get(cacheKey);

            if (retrieveObj != null)
            {
                // Return view with result
                return View();
            }
            else
            {
                cacheEntry = DateTime.MaxValue;

                var cacheEntryOptions = new DistributedCacheEntryOptions
                {
                    SlidingExpiration = TimeSpan.FromMinutes(30)
                };

                _cache.Set(cacheKey, new byte[1024], cacheEntryOptions);

                return View(cacheEntry);
            }
        }
        catch (Exception ex)
        {
            // Log error here if needed
            return StatusCode(500, $"Cache error: {ex.Message}");
        }
    }
}

Additional Resources

NCache provides a sample application for session caching on GitHub.

See Also

.NET: Alachisoft.NCache.Caching.Distributed namespace.

Contact Us

PHONE

+1 214-619-2601   (US)

+44 20 7993 8327   (UK)

 
EMAIL

sales@alachisoft.com

support@alachisoft.com

NCache
  • Edition Comparison
  • NCache Architecture
  • Benchmarks
Download
Pricing
Try Playground

Deployments
  • Cloud (SaaS & Software)
  • On-Premises
  • Kubernetes
  • Docker
Technical Use Cases
  • ASP.NET Sessions
  • ASP.NET Core Sessions
  • Pub/Sub Messaging
  • Real-Time ASP.NET SignalR
  • Internet of Things (IoT)
  • NoSQL Database
  • Stream Processing
  • Microservices
Resources
  • Magazine Articles
  • Third-Party Articles
  • Articles
  • Videos
  • Whitepapers
  • Shows
  • Talks
  • Blogs
  • Docs
Customer Case Studies
  • Testimonials
  • Customers
Support
  • Schedule a Demo
  • Forum (Google Groups)
  • Tips
Company
  • Leadership
  • Partners
  • News
  • Events
  • Careers
Contact Us

  • EnglishChinese (Simplified)FrenchGermanItalianJapaneseKoreanPortugueseSpanish

  • Contact Us
  •  
  • Sitemap
  •  
  • Terms of Use
  •  
  • Privacy Policy
© Copyright Alachisoft 2002 - . All rights reserved. NCache is a registered trademark of Diyatech Corp.
Back to top