Quickstart: Use Azure Cache for Redis with an ASP.NET Core web app

In this quickstart, you incorporate Azure Cache for Redis into an ASP.NET Core web application that connects to Azure Cache for Redis to store and retrieve data from the cache.

There are also caching providers in .NET core. To quickly start using Redis with minimal changes to your existing code, see:

Skip to the code on GitHub

Clone the https://github.com/Azure-Samples/azure-cache-redis-samples GitHub repo and navigate to the quickstart/aspnet-core directory to view the completed source code for the steps ahead.

The quickstart/aspnet-core directory is also configured as an Azure Developer CLI (azd) template. Use the open-source azd tool to streamline the provisioning and deployment from a local environment to Azure. Optionally, run the azd up command to automatically provision an Azure Cache for Redis instance, and to configure the local sample app to connect to it:

azd up

Explore the eShop sample

As a next step, you can see a real-world scenario eShop application demonstrating the ASP.NET core caching providers: ASP.NET core eShop using Redis caching providers.

Features included:

  • Redis Distributed Caching
  • Redis session state provider

Deployment instructions are in the README.md.

Prerequisites

Create a cache

  1. To create a cache, sign in to the Azure portal. On the portal menu, select Create a resource.

    Sceenshot that shows the Create a resource option highlighted on the left navigation pane in the Azure portal.

  2. On the Get Started pane, enter Azure Cache for Redis in the search bar. In the search results, find Azure Cache for Redis, and then select Create.

    Screenshot that shows Azure Marketplace with Azure Cache for Redis in the search box, and the Create button is highlighted.

  3. On the New Redis Cache pane, on the Basics tab, configure the following settings for your cache:

    Setting Action Description
    Subscription Select your Azure subscription. The subscription to use to create the new instance of Azure Cache for Redis.
    Resource group Select a resource group, or select Create new and enter a new resource group name. A name for the resource group in which to create your cache and other resources. By putting all your app resources in one resource group, you can easily manage or delete them together.
    DNS name Enter a unique name. The cache name must be a string of 1 to 63 characters that contains only numbers, letters, and hyphens. The name must start and end with a number or letter, and it can't contain consecutive hyphens. Your cache instance's host name is \<DNS name>.redis.cache.windows.net.
    Location Select a location. An Azure region that is near other services that use your cache.
    Cache SKU Select a SKU. The SKU determines the size, performance, and feature parameters that are available for the cache. For more information, see Azure Cache for Redis overview.
    Cache size Select a cache size. For more information, see Azure Cache for Redis overview.
  4. Select the Networking tab or select Next: Networking.

  5. On the Networking tab, select a connectivity method to use for the cache.

  6. Select the Advanced tab or select Next: Advanced.

  7. On the Advanced tab, select the Microsoft Entra Authentication checkbox to enable Microsoft Entra authentication.

    Screenshot showing the Advanced pane and the available option to select.

    Important

    For optimal security, we recommend that you use Microsoft Entra ID with managed identities to authorize requests against your cache if possible. Authorization by using Microsoft Entra ID and managed identities provides superior security and ease of use over shared access key authorization. For more information about using managed identities with your cache, see Use Microsoft Entra ID for cache authentication.

  8. (Optional) Select the Tags tab or select Next: Tags.

  9. (Optional) On the Tags tab, enter a tag name and value if you want to categorize your cache resource.

  10. Select the Review + create button.

    On the Review + create tab, Azure automatically validates your configuration.

  11. After the green Validation passed message appears, select Create.

A new cache deployment occurs over several minutes. You can monitor the progress of the deployment on the Azure Cache for Redis Overview pane. When Status displays Running, the cache is ready to use.

Enable Microsoft Entra ID authentication on your cache

If you have a cache, check to see if Microsoft Entra Authentication has been enabled. If not, then enable it. We recommend using Microsoft Entra ID for your apps.

  1. In the Azure portal, select the Azure Cache for Redis instance where you'd like to use Microsoft Entra token-based authentication.

  2. Select Authentication from the Resource menu.

  3. Check in the working pane to see if Enable Microsoft Entra Authentication is checked. If so, you can move on.

  4. Select Enable Microsoft Entra Authentication, and enter the name of a valid user. The user you enter is automatically assigned Data Owner Access Policy by default when you select Save. You can also enter a managed identity or service principal to connect to your cache instance.

    Screenshot showing authentication selected in the resource menu and the enable Microsoft Entra authentication checked.

  5. A popup dialog box displays asking if you want to update your configuration, and informing you that it takes several minutes. Select Yes.

    Important

    Once the enable operation is complete, the nodes in your cache instance reboots to load the new configuration. We recommend performing this operation during your maintenance window or outside your peak business hours. The operation can take up to 30 minutes.

For information on using Microsoft Entra ID with Azure CLI, see the references pages for identity.

Add the Redis access policy

You need to assign a data access policy to the identity that accesses Azure Cache for Redis. For this example, you assign a data access policy to the same Microsoft Entra ID account you use to log into the Azure CLI or Visual Studio.

  1. Select Settings Resource menu on the cache and select the Data Access Configuration.

  2. On the Data Access Configuration page, select Add > New Redis User from the top navigation.

    Screenshot showing the data access configuration screen.

  3. On the New Redis User page, select the Data Contributor policy, and select Next: Redis Users.

  4. Choose + Select Member to open the flyout menu. Search for your user account and select it from the results.

    Screenshot showing the Redis user tab in the working pane with select member highlighted with a red box.

  5. Select Review + assign to assign the policy to the selected user.

Add a local secret for the host name

In your command window, execute the following command to store a new secret named RedisHostName, after replacing the placeholders, including angle brackets, for your cache name and primary access key:

dotnet user-secrets set RedisHostName "<cache-name>.redis.cache.windows.net"

For using Azure Managed Redis (preview) instance, store a new secret named RedisHostName as below:

dotnet user-secrets set RedisHostName "<cache-name>.<region>.redis.azure.net"

## Connect to the cache with RedisConnection

The `RedisConnection` class manages the connection to your cache. The connection is made in this statement in `HomeController.cs` in the *Controllers* folder:

```csharp
_redisConnection = await _redisConnectionFactory;

The RedisConnection.cs class includes the StackExchange.Redis and Azure.Identity namespaces at the top of the file to include essential types to connect to Azure Cache for Redis.

using StackExchange.Redis;
using Azure.Identity;

The RedisConnection code ensures that there's always a healthy connection to the cache by managing the ConnectionMultiplexer instance from StackExchange.Redis. The RedisConnection class recreates the connection when a connection is lost and unable to reconnect automatically.

For more information, see StackExchange.Redis and the code in a GitHub repo.

Layout views in the sample

The home page layout for this sample is stored in the _Layout.cshtml file. From this page, you start the actual cache testing by clicking the Azure Cache for Redis Test from this page.

  1. Open Views\Shared\_Layout.cshtml.

  2. You should see in <div class="navbar-header">:

    <a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="RedisCache">Azure Cache for Redis Test</a>
    

Screenshot of welcome page.

Showing data from the cache

From the home page, you select Azure Cache for Redis Test to see the sample output.

  1. In Solution Explorer, expand the Views folder, and then right-click the Home folder.

  2. You should see this code in the RedisCache.cshtml file.

    @{
        ViewBag.Title = "Azure Cache for Redis Test";
    }
    
    <h2>@ViewBag.Title.</h2>
    <h3>@ViewBag.Message</h3>
    <br /><br />
    <table border="1" cellpadding="10">
        <tr>
            <th>Command</th>
            <th>Result</th>
        </tr>
        <tr>
            <td>@ViewBag.command1</td>
            <td><pre>@ViewBag.command1Result</pre></td>
        </tr>
        <tr>
            <td>@ViewBag.command2</td>
            <td><pre>@ViewBag.command2Result</pre></td>
        </tr>
        <tr>
            <td>@ViewBag.command3</td>
            <td><pre>@ViewBag.command3Result</pre></td>
        </tr>
        <tr>
            <td>@ViewBag.command4</td>
            <td><pre>@ViewBag.command4Result</pre></td>
        </tr>
        <tr>
            <td>@ViewBag.command5</td>
            <td><pre>@ViewBag.command5Result</pre></td>
        </tr>
    </table>
    

Run the app locally

  1. Execute the following command in your command window to build the app:

    dotnet build
    
  2. Then run the app with the following command:

    dotnet run
    
  3. Browse to https://localhost:5001 in your web browser.

  4. Select Azure Cache for Redis Test in the navigation bar of the web page to test cache access.

Screenshot of simple test completed locally.

Clean up resources

If you want to continue to use the resources you created in this article, keep the resource group.

Otherwise, if you're finished with the resources, you can delete the Azure resource group that you created to avoid charges.

Important

Deleting a resource group is irreversible. When you delete a resource group, all the resources in it are permanently deleted. Make sure that you do not accidentally delete the wrong resource group or resources. If you created the resources inside an existing resource group that contains resources you want to keep, you can delete each resource individually instead of deleting the resource group.

To delete a resource group

  1. Sign in to the Azure portal, and then select Resource groups.

  2. Select the resource group you want to delete.

    If there are many resource groups, use the Filter for any field... box, type the name of your resource group you created for this article. Select the resource group in the results list.

    Screenshot showing a list of resource groups to delete in the working pane.

  3. Select Delete resource group.

  4. You're asked to confirm the deletion of the resource group. Type the name of your resource group to confirm, and then select Delete.

    Screenshot showing a form that requires the resource name to confirm deletion.

After a few moments, the resource group and all of its resources are deleted.