Quickstart: Use Azure 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:
- ASP.NET core Output Cache provider
- ASP.NET core Distributed Caching provider
- ASP.NET core Redis session provider
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
Prerequisites
- Azure subscription - create one
- .NET Core SDK
Create an Azure Cache for Redis instance
To create a cache, sign in to the Azure portal and select Create a resource.
On the Get Started page, type Azure Cache for Redis in the search box. Then, select Create.
On the New Redis Cache page, configure the settings for your cache.
Setting Choose a value Description Subscription Drop down and select your subscription. The subscription under which to create this new Azure Cache for Redis instance. Resource group Drop down and select a resource group, or select Create new and enter a new resource group name. 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 between 1 and 63 characters that contain only numbers, letters, or hyphens. The name must start and end with a number or letter, and can't contain consecutive hyphens. Your cache instance's host name is <DNS name>.redis.cache.chinacloudapi.cn. Location Drop down and select a location. Select a region near other services that use your cache. Cache SKU Drop down and select a SKU. The SKU determines the size, performance, and features parameters that are available for the cache. For more information, see Azure Cache for Redis Overview. Cache size Drop down and select a size of your cache For more information, see Azure Cache for Redis Overview. Select the Networking tab or select the Networking button at the bottom of the page.
In the Networking tab, select your connectivity method.
Select the Next: Advanced tab or select the Next: Advanced button on the bottom of the page to see the Advanced tab.
- For Basic or Standard caches, toggle the selection for a non-TLS port. You can also select if you want to enable Microsoft Entra Authentication.
- For a Premium cache, configure the settings for non-TLS port, clustering, managed identity, and data persistence. You can also select if you want to enable Microsoft Entra Authentication.
Select the Next: Tags tab or select the Next: Tags button at the bottom of the page.
Optionally, in the Tags tab, enter the name and value if you wish to categorize the resource.
Select Review + create. You're taken to the Review + create tab where Azure validates your configuration.
After the green Validation passed message appears, select Create.
It takes a while for a cache to create. You can monitor progress on the Azure Cache for Redis Overview page. When Status shows as Running, the cache is ready to use.
Microsoft Entra ID Authentication (recommended)
Use Microsoft Entra ID authentication on your cache
Azure Redis caches have Microsoft Entra Authentication enabled by default. Access keys are disabled by default.
Important
Microsoft recommends using Microsoft Entra ID authentication for the most secure authentication experience instead of using passwords or access keys. The authentication described in this section of the article uses access keys, which require a very high degree of trust in the application and carries risks not present when using Microsoft Entra ID. Use the approach in this document only when Microsoft Entra ID authentication is not viable.
In the Azure portal, select the cache where you'd like to use Microsoft Entra token-based authentication.
Select Authentication from the Resource menu.
Select Select member 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.
For information on using Microsoft Entra ID with Azure CLI, see the reference pages for identity.
Install the Library for using Microsoft Entra ID Authentication
The Azure.StackExchange.Redis library contains the Microsoft Entra ID authentication method for connecting to Azure Redis services using Microsoft Entra ID. It is applicable to all Azure Cache for Redis.
dotnet add package Microsoft.Azure.StackExchangeRedis
Connect to the cache using Microsoft Entra ID
Include the libraries in your code
using Azure.Identity; using StackExchange.Redis
Using the default Azure credentials to authenticate the client connection. This enables your code to use the signed-in user credential when running locally, and an Azure managed identity when running in Azure without code change.
var configurationOptions = await ConfigurationOptions.Parse($"{_redisHostName}").ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential()); ConnectionMultiplexer _newConnection = await ConnectionMultiplexer.ConnectAsync(configurationOptions); IDatabase Database = _newConnection.GetDatabase();
To edit the appsettings.json file
Edit the appsettings.json file. Then add the following content:
"_redisHostName":"<cache-hostname>"
Replace
<cache-hostname>
with your cache host name as it appears in the Overview blade of Azure Portal.For example, with Azure Cache for Redis: my-redis.chinanorth.chinacloudapi.cn:6380
Save the file.
For more information, see StackExchange.Redis and the code in a GitHub repo.
Run the app locally
Execute the following command in your command window to build the app:
dotnet build
Then run the app with the following command:
dotnet run
Browse to
https://localhost:5001
in your web browser.Select Azure Cache for Redis Test in the navigation bar of the web page to test cache access.
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
Sign in to the Azure portal, and then select Resource groups.
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.
Select Delete resource group.
You're asked to confirm the deletion of the resource group. Type the name of your resource group to confirm, and then select Delete.
After a few moments, the resource group and all of its resources are deleted.