Quickstart: Use Azure Cache for Redis with an ASP.NET web app
In this quickstart, you use Visual Studio 2019 to create an ASP.NET web application that connects to Azure Cache for Redis to store and retrieve data from the cache. You then deploy the app to Azure App Service.
Skip to the code on GitHub
Clone the repo https://github.com/Azure-Samples/azure-cache-redis-samples/tree/main/quickstart/aspnet on GitHub.
Prerequisites
- Azure subscription - create one
- Visual Studio 2019 with the ASP.NET and web development and Azure development workloads.
Create a cache
Next, you create the cache for the app.
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.
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.
In the Azure portal, select the Azure Cache for Redis instance where you'd like to use Microsoft Entra token-based authentication.
Select Authentication from the Resource menu.
Check in the working pane to see if Enable Microsoft Entra Authentication is checked. If so, you can move on.
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.
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.
To edit the CacheSecrets.config file
Create a file on your computer named CacheSecrets.config. Put it in a location where it won't be checked in with the source code of your sample application. For this quickstart, the CacheSecrets.config file is located at C:\AppSecrets\CacheSecrets.config.
Edit the Web.config file. Then add the following content:
<appSettings> <add key="RedisHostName" value="<cache-hostname>:<port-number>"/> </appSettings>
Replace
<cache-hostname>
with your cache host name as it appears in the Overview blade of Azure PortalReplace
<port-number>
with your cache host port number.Save the file.
Update the MVC application
In this section, you can see an MVC application that presents a view that displays a simple test against Azure Cache for Redis.
Install StackExchange.Redis
Your solution needs the StackExchange.Redis
package to run. Install it, with this procedure:
To configure the app to use the StackExchange.Redis NuGet package for Visual Studio, select Tools > NuGet Package Manager > Package Manager Console.
Run the following command from the
Package Manager Console
window:Install-Package Microsoft.Azure.StackExchangeRedis
The NuGet package downloads and adds the required assembly references for your client application to access Azure Cache for Redis with the
Microsoft.Azure.StackExchangeRedis
client.
Connect to the cache with RedisConnection
The connection to your cache is managed by the RedisConnection
class. The connection is first made in this statement from ContosoTeamStats/Controllers/HomeController.cs
:
private static Task<RedisConnection> _redisConnectionFactory = RedisConnection.InitializeAsync(redisHostName: ConfigurationManager.AppSettings["RedisHostName"].ToString());
In RedisConnection.cs
, you see the StackExchange.Redis
namespace has been added to the code. This is needed for the RedisConnection
class.
using StackExchange.Redis;
The RedisConnection
code ensures that there is 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.
The following line of code uses Microsoft Entra ID to connect to Azure Cache for Redis without password.
var configurationOptions = await ConfigurationOptions.Parse($"{_redisHostName}").ConfigureForAzureWithTokenCredentialAsync(new DefaultAzureCredential());
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.
In Solution Explorer, expand the Views > Shared folder. Then open the _Layout.cshtml file.
You see the following line in
<div class="navbar-header">
.@Html.ActionLink("Azure Cache for Redis Test", "RedisCache", "Home", new { area = "" }, new { @class = "navbar-brand" })
Showing data from the cache
From the home page, you select Azure Cache for Redis Test to see the sample output.
In Solution Explorer, expand the Views folder, and then right-click the Home folder.
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
By default, the project is configured to host the app locally in IIS Express for testing and debugging.
To run the app locally
In Visual Studio, select Debug > Start Debugging to build and start the app locally for testing and debugging.
In the browser, select Azure Cache for Redis Test on the navigation bar.
In the following example, the
Message
key previously had a cached value, which was set by using the Azure Cache for Redis console in the portal. The app updated that cached value. The app also executed thePING
andCLIENT LIST
commands.
Publish and run in Azure
After you successfully test the app locally, you can deploy the app to Azure and run it in the cloud.
To publish the app to Azure
In Visual Studio, right-click the project node in Solution Explorer. Then select Publish.
Select Azure App Service, select Create New, and then select Publish.
In the Create App Service dialog box, make the following changes:
Setting Recommended value Description App name Use the default. The app name is the host name for the app when it's deployed to Azure. The name might have a timestamp suffix added to it to make it unique if necessary. Subscription Choose your Azure subscription. This subscription is charged for any related hosting costs. If you have multiple Azure subscriptions, verify that the subscription that you want is selected. Resource group Use the same resource group where you created the cache (for example, TestResourceGroup). The resource group helps you manage all resources as a group. Later, when you want to delete the app, you can just delete the group. App Service plan Select New, and then create a new App Service plan named TestingPlan.
Use the same Location you used when creating your cache.
Choose Free for the size.An App Service plan defines a set of compute resources for a web app to run with. After you configure the App Service hosting settings, select Create.
Monitor the Output window in Visual Studio to see the publishing status. After the app has been published, the URL for the app is logged:
Add the app setting for the cache
After the new app has been published, add a new app setting. This setting is used to store the cache connection information.
To add the app setting
Type the app name in the search bar at the top of the Azure portal to find the new app you created.
Add a new app setting named CacheConnection for the app to use to connect to the cache. Use the same value you configured for
RedisHostName
in your web.config file.
Run the app in Azure
In your browser, go to the URL for the app. The URL appears in the results of the publishing operation in the Visual Studio output window. It's also provided in the Azure portal on the overview page of the app you created.
Select Azure Cache for Redis Test on the navigation bar to test cache access as you did with the local version.
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.