Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To use Redis as a shared cache in an ASP.NET Core app, install the Microsoft.Extensions.Caching.StackExchangeRedis provider, register it with AddStackExchangeRedisCache, and inject IDistributedCache where your application needs cached data. The abstraction stores string keys and byte-array values, so structured objects must be serialized before storage and deserialized after retrieval.

What Redis caching provides in .NET

Redis is one provider for .NET’s distributed-cache abstraction. In ASP.NET Core, the provider package is Microsoft.Extensions.Caching.StackExchangeRedis, and its implementation uses StackExchange.Redis as the client. Application code can depend on IDistributedCache rather than constructing the Redis implementation directly.

A distributed cache is useful when multiple app servers need to read and write the same cached data. Unlike an in-process cache, the cache lives in an external service, so using it requires network I/O and adds some latency. Microsoft describes these trade-offs in its .NET caching overview.

Install and register the Redis provider

Add the Microsoft.Extensions.Caching.StackExchangeRedis NuGet package to the ASP.NET Core project, selecting a stable package version compatible with the project’s target framework. Do not choose a preview package simply because a preview API reference appears in search results; verify the current stable version when implementing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In Program.cs, register the provider and read its connection string from configuration:

builder.Services.AddStackExchangeRedisCache(options =>
{
    options.Configuration = builder.Configuration.GetConnectionString("MyRedisConStr");
    options.InstanceName = "SampleInstance";
});

MyRedisConStr is the connection-string key expected by this example; change it to match your configuration. InstanceName is an optional prefix used for cache keys. Microsoft’s ASP.NET Core distributed-caching guide documents this registration pattern.

Keep connection details out of source control

Do not commit real Redis credentials or connection strings in source files or repository configuration. For local development, Microsoft recommends secure storage such as Secret Manager; for Azure deployments, Azure Key Vault is an example of a secure store. Supply the value through your environment’s configuration so the same application registration can use the appropriate connection in each environment.

Use the cache through IDistributedCache

Inject IDistributedCache into the service or component that needs cached data. Its keys are strings and its values are byte arrays. The interface offers synchronous and asynchronous methods for getting, setting, refreshing, and removing entries; web request paths commonly use the asynchronous variants.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
using Microsoft.Extensions.Caching.Distributed;

public sealed class ProductService
{
    private readonly IDistributedCache _cache;

    public ProductService(IDistributedCache cache)
    {
        _cache = cache;
    }
}

Using the interface keeps application code tied to the cache contract rather than to the Redis provider class. That is useful when the application’s cache implementation is selected through dependency injection.

Store structured data with serialization

Because IDistributedCache accepts bytes, convert an object to a representation such as JSON, encode that text as UTF-8, and then pass the bytes to SetAsync. On a cache hit, convert the retrieved bytes back to text and deserialize the object. Microsoft’s caching guidance demonstrates JSON serialization with UTF-8 conversion.

using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Caching.Distributed;

public async Task<Product?> GetProductAsync(
    string key,
    CancellationToken cancellationToken)
{
    byte[]? cachedBytes = await _cache.GetAsync(key, cancellationToken);

    if (cachedBytes is not null)
    {
        string json = Encoding.UTF8.GetString(cachedBytes);
        return JsonSerializer.Deserialize<Product>(json);
    }

    Product? product = await LoadProductAsync(key, cancellationToken);
    if (product is null)
    {
        return null;
    }

    string productJson = JsonSerializer.Serialize(product);
    byte[] productBytes = Encoding.UTF8.GetBytes(productJson);

    var cacheOptions = new DistributedCacheEntryOptions
    {
        AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
    };

    await _cache.SetAsync(key, productBytes, cacheOptions, cancellationToken);
    return product;
}

LoadProductAsync represents the application’s own data-loading method. The ten-minute expiration above is an example, not a universal recommendation: choose a lifetime based on how long the cached data remains useful and how much staleness the application can tolerate. The code also leaves the cache untouched when no product is found; whether to cache missing results is an application-specific decision.

Choose expiration and handle updates

Pass a DistributedCacheEntryOptions object when setting an entry to specify an absolute or sliding expiration. Absolute expiration sets a point after which the item expires; sliding expiration is extended as the entry is accessed. Refresh and RefreshAsync reset the sliding-expiration timeout when one is configured.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set expiration according to the data’s freshness needs, and decide how changes to the source data will invalidate or replace cached entries. The .NET documentation does not establish one Redis-specific TTL that fits every application.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Decide whether Redis is the right cache

Use Redis when application instances need a cache held outside each app server, particularly when multiple servers must share cached entries. The external service provides that shared location, at the cost of network I/O and some added latency.

When an in-memory implementation is enough

AddDistributedMemoryCache implements the same interface but holds items in the current app server’s memory. It can be suitable for development and testing and for some single-server production scenarios where memory is not an issue. It is not a shared store across app-server nodes. Microsoft’s documentation cautions that it is not a viable production implementation when a true distributed cache is required.

Other distributed-cache providers

Redis is not mandatory for every .NET application. The same broad abstraction has providers for systems including SQL Server, PostgreSQL, Cosmos DB, and NCache. Compare the options based on the infrastructure you already operate, hosting fit, operational ownership, latency needs, and whether several app instances must share cache data. The ASP.NET Core distributed-caching documentation describes provider choices, including Redis.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Common implementation mistakes to avoid

  • Putting credentials in code: load the connection string from secure configuration rather than committing it to the repository.
  • Passing an object directly to the cache: serialize structured data to bytes before calling SetAsync, and deserialize bytes returned by GetAsync.
  • Assuming in-memory caching is shared: AddDistributedMemoryCache keeps data on the current server, so different nodes do not share its entries.
  • Choosing expiration without considering staleness: align absolute or sliding expiration with how current the data must be and how updates invalidate cached values.

For API details, consult the Microsoft Learn references for the Redis cache namespace and the RedisCache class; check the target framework and stable package release that apply to your project.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.