Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Add an Infinispan cache to your ASP.NET application

July 7, 2022
Vittorio Rigamonti
Related topics:
.NETLinuxOpen source
Related products:
Red Hat Enterprise Linux

    The open source Infinispan data store is popular for in-memory operations. A .NET Core application can now easily integrate Infinispan as a caching service or session provider. This article provides basic information on how to do that in C# on Linux.

    What you need:

    • .NET 6.0+ installed on your system
    • Access to get packages from NuGet
    • Access to an Infinispan server

    On the Infinispan server, create a cache named default listening on the loopback host and port 127.0.0.1:11222, without authentication.

    Create the application

    You are going to work on an ASP.NET Core application, so run the following command to generate a new application scaffold:

    dotnet new webapp -lang 'C#' -n Infinispan.Example.Caching -f net6.0

    This command creates a new folder with an empty but working ASP.NET Core application. Run the application as follows:

    cd Infinispan.Example.Caching
    dotnet run

    Check the application's log message for its HTTP or HTTPS URL and enter it into your browser to see the application's display.

    Add Infinispan as a cache

    The application requires the Infinispan caching package, so add it as follows:

    dotnet add package Infinispan.Hotrod.Caching --version 0.0.1-alpha3

    This package provides an IDistibutedCache implementation based on the Infinispan C# client, imported as a dependency.

    Set up Infinispan as a cache provider

    An ASP.NET Core application (6.0) provides all the services and pipeline setup in the Program.cs file. To this file, you need to add the Infinispan client configuration in the service setup, as well as session management in the process pipeline. Set the cache entries to expire after 10 seconds of idle time. Program.cs should now look like this:

    using Infinispan.Hotrod.Core;
    using Infinispan.Hotrod.Caching.Distributed;
    var builder = WebApplication.CreateBuilder(args);
    
    // Add services to the container.
    // Infinispan default setup is used:
    // 127.0.0.1:11222 cacheName: default
    builder.Services.AddInfinispanCache();
    builder.Services.AddSession(options =>
    {
        options.IdleTimeout = TimeSpan.FromSeconds(10);
        options.Cookie.HttpOnly = true;
        options.Cookie.IsEssential = true;
    });
    
    builder.Services.AddRazorPages();
    
    var app = builder.Build();
    
    // Configure the HTTP request pipeline.
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    
    app.UseRouting();
    
    app.UseAuthorization();
    app.UseSession();
    
    app.MapRazorPages();
    
    app.Run();

    Add business code

    Our business code is very simple: It presents some information (the user name, the age of the session, and the first access time) to the user as a result of a request. The data is fetched from the session cache if available there and computed by the program otherwise. This logic is implemented in the model file Pages/Index.cshtml.cs:

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    
    namespace Infinispan.Example.Caching.Pages
    {
    
        public class IndexModel : PageModel
        {
            private readonly ILogger<IndexModel> _logger;
    
            public IndexModel(ILogger<IndexModel> logger)
            {
                _logger = logger;
            }
    
            public const string SessionKeyName = "_Name";
            public const string SessionKeyAge = "_Age";
            public const string SessionKeyFirstAccess = "_FirstAccess";
            public static Random RndSource = new Random();
            public string DataSource { get; private set; } = "";
            public void OnGet()
            {
                // Requires: using Microsoft.AspNetCore.Http;
                if (string.IsNullOrEmpty(HttpContext.Session.GetString(SessionKeyName)))
                {
                    DataSource = "Computed";
                    HttpContext.Session.SetString(SessionKeyName, "Mickey");
                    HttpContext.Session.SetInt32(SessionKeyAge, RndSource.Next(100));
                    HttpContext.Session.SetString(SessionKeyFirstAccess, DateTime.Now.ToString());
                    return;
                }
                DataSource = "Cache";
            }
        }
    }

    The output is generated from a file named Pages/Index.cshtml:

    @page
    @using Infinispan.Example.Caching.Pages
    @using Microsoft.AspNetCore.Http
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <h2>The time on the server is @DateTime.Now</h2>
    
        <h2>Name (@Model.DataSource): @HttpContext.Session.GetString(IndexModel.SessionKeyName)</h2>
        <h2>Age (@Model.DataSource): @HttpContext.Session.GetInt32(IndexModel.SessionKeyAge)</h2>
        <h2>First Access Date (@Model.DataSource): @HttpContext.Session.GetString(IndexModel.SessionKeyFirstAccess)</h2>
        <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    </div>

    Easy ASP.NET access to Infinispan

    Everything is now in place for the show. Run your application again and check the output in the browser. The Age and the First Access Date field are computed the first time and cached for 10 seconds. The session itself expires after 10 seconds of idle time, as configured in the services configuration. Therefore, the cached values are reused by the application if requests come in quick succession.

    This article has demonstrated how easily you can integrate Infinispan as a distributed cache and session provider for ASP.Net Core applications.

    Explore more .NET tutorials on Red Hat Developer:

    • Hello Podman using .NET
    • Debug .NET applications running in local containers with VS Code
    • Deploy .NET applications on Red Hat OpenShift using Helm
    Last updated: November 5, 2025

    Related Posts

    • Deploy Infinispan automatically with Ansible

    • Infinispan’s Java 8 Streams Capabilities

    Recent Posts

    • Red Hat Enterprise Linux 10.2 and 9.8: Top features for developers

    • What GPU kernels mean for your distributed inference

    • Debugging image mode with Red Hat OpenShift 4.20: A practical guide

    • EvalHub: Because "looks good to me" isn't a benchmark

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    What’s up next?

    Red Hat Insights API

    Find out how to get actionable intelligence using Red Hat Lightspeed APIs so you can identify and address operational and vulnerability risks in your Red Hat Enterprise Linux environments before an issue results in downtime.

    Get the cheat sheet
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.