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.


Create the Visual Studio project

  1. Open Visual Studio, and then and select File >New > Project.

  2. In the New Project dialog box, take the following steps:

    Create project

    a. In the Templates list, expand the Visual C# node.

    b. Select Cloud.

    c. Select ASP.NET Web Application.

    d. Verify that .NET Framework 4.5.2 or higher is selected.

    e. In the Name box, give the project a name. For this example, we used ContosoTeamStats.

    f. Select OK.

  3. Select MVC as the project type.

  4. Make sure that No Authentication is specified for the Authentication settings. Depending on your version of Visual Studio, the default Authentication setting might be something else. To change it, select Change Authentication and then No Authentication.

  5. Select OK to create the project.

Create a cache

Next, you create the cache for the app.

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

    Create a resource is highlighted in the left navigation pane.

  2. On the New page, select Databases and then select Azure Cache for Redis.

    On New, Databases is highlighted, and Azure Cache for Redis is highlighted.

  3. On the New Redis Cache page, configure the settings for your new cache.

    Setting Suggested value Description
    DNS name Enter a globally unique name. The cache name must be a string between 1 and 63 characters that contains 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 will be <DNS name>.redis.cache.windows.net.
    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.
    Location Drop down and select a location. Select a region near other services that will use your cache.
    Pricing tier Drop down and select a Pricing tier. The pricing tier determines the size, performance, and features that are available for the cache. For more information, see Azure Cache for Redis Overview.
  4. Select the Networking tab or click the Networking button at the bottom of the page.

  5. In the Networking tab, select your connectivity method.

  6. Select the Next: Advanced tab or click the Next: Advanced button on the bottom of the page.

  7. In the Advanced tab for a basic or standard cache instance, select the enable toggle if you want to enable a non-TLS port. You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

    Redis version 4 or 6.

  8. In the Advanced tab for premium cache instance, configure the settings for non-TLS port, clustering, and data persistence. You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

  9. Select the Next: Tags tab or click the Next: Tags button at the bottom of the page.

  10. Optionally, in the Tags tab, enter the name and value if you wish to categorize the resource.

  11. Select Review + create. You're taken to the Review + create tab where Azure validates your configuration.

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

It takes a while for the 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.

Retrieve host name, ports, and access keys from the Azure portal

To connect to an Azure Cache for Redis instance, cache clients need the host name, ports, and a key for the cache. Some clients might refer to these items by slightly different names. You can get the host name, ports, and keys from the Azure portal.

  • To get the access keys, from your cache left navigation, select Access keys.

    Azure Cache for Redis keys

  • To get the host name and ports, from your cache left navigation, select Properties. The host name is of the form <DNS name>.redis.cache.windows.net.

    Azure Cache for Redis properties

To edit the CacheSecrets.config file

  1. 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.

  2. Edit the CacheSecrets.config file. Then add the following content:

        <add key="CacheConnection" value="<cache-name>.redis.cache.windows.net,abortConnect=false,ssl=true,allowAdmin=true,password=<access-key>"/>
  3. Replace <cache-name> with your cache host name.

  4. Replace <access-key> with the primary key for your cache.


    You can use the secondary access key during key rotation as an alternate key while you regenerate the primary access key.

  5. Save the file.

Update the MVC application

In this section, you update the application to support a new view that displays a simple test against Azure Cache for Redis.

Update the web.config file with an app setting for the cache

When you run the application locally, the information in CacheSecrets.config is used to connect to your Azure Cache for Redis instance. Later you deploy this application to Azure. At that time, you configure an app setting in Azure that the application uses to retrieve the cache connection information instead of this file.

Because the file CacheSecrets.config isn't deployed to Azure with your application, you only use it while testing the application locally. Keep this information as secure as possible to prevent malicious access to your cache data.

To update the web.config file

  1. In Solution Explorer, double-click the web.config file to open it.


  2. In the web.config file, find the <appSetting> element. Then add the following file attribute. If you used a different file name or location, substitute those values for the ones that are shown in the example.

  • Before: <appSettings>
  • After: <appSettings file="C:\AppSecrets\CacheSecrets.config">

The ASP.NET runtime merges the contents of the external file with the markup in the <appSettings> element. The runtime ignores the file attribute if the specified file can't be found. Your secrets (the connection string to your cache) aren't included as part of the source code for the application. When you deploy your web app to Azure, the CacheSecrets.config file isn't deployed.

To configure the application to use StackExchange.Redis

  1. To configure the app to use the StackExchange.Redis NuGet package for Visual Studio, select Tools > NuGet Package Manager > Package Manager Console.

  2. Run the following command from the Package Manager Console window:

    Install-Package StackExchange.Redis
  3. The NuGet package downloads and adds the required assembly references for your client application to access Azure Cache for Redis with the StackExchange.Azure Cache for Redis client. If you prefer to use a strong-named version of the StackExchange.Redis client library, install the StackExchange.Redis.StrongName package.

To update the HomeController and Layout

  1. In Solution Explorer, expand the Controllers folder, and then open the HomeController.cs file.

  2. Add the following two using statements at the top of the file to support the cache client and app settings.

    using System.Configuration;
    using StackExchange.Redis;
  3. Add the following method to the HomeController class to support a new RedisCache action that runs some commands against the new cache.

    public ActionResult RedisCache()
        ViewBag.Message = "A simple example with Azure Cache for Redis on ASP.NET.";
        IDatabase cache = Connection.GetDatabase();
        // Perform cache operations using the cache object...
        // Simple PING command
        ViewBag.command1 = "PING";
        ViewBag.command1Result = cache.Execute(ViewBag.command1).ToString();
        // Simple get and put of integral data types into the cache
        ViewBag.command2 = "GET Message";
        ViewBag.command2Result = cache.StringGet("Message").ToString();
        ViewBag.command3 = "SET Message \"Hello! The cache is working from ASP.NET!\"";
        ViewBag.command3Result = cache.StringSet("Message", "Hello! The cache is working from ASP.NET!").ToString();
        // Demonstrate "SET Message" executed as expected...
        ViewBag.command4 = "GET Message";
        ViewBag.command4Result = cache.StringGet("Message").ToString();
        // Get the client list, useful to see if connection list is growing...
        ViewBag.command5 = "CLIENT LIST";
        StringBuilder sb = new StringBuilder();
        var endpoint = (System.Net.DnsEndPoint)Connection.GetEndPoints()[0];
        var server = Connection.GetServer(endpoint.Host, endpoint.Port);
        var clients = server.ClientList();
        sb.AppendLine("Cache response :");
        foreach (var client in clients)
        ViewBag.command5Result = sb.ToString();
        return View();
    private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        string cacheConnection = ConfigurationManager.AppSettings["CacheConnection"].ToString();
        return ConnectionMultiplexer.Connect(cacheConnection);
    public static ConnectionMultiplexer Connection
            return lazyConnection.Value;
  4. In Solution Explorer, expand the Views > Shared folder. Then open the _Layout.cshtml file.


    @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })


    @Html.ActionLink("Azure Cache for Redis Test", "RedisCache", "Home", new { area = "" }, new { @class = "navbar-brand" })

To add a new RedisCache view

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

  2. In the Add View dialog box, enter RedisCache for the View Name. Then select Add.

  3. Replace the code in the RedisCache.cshtml file with the following code:

        ViewBag.Title = "Azure Cache for Redis Test";
    <br /><br />
    <table border="1" cellpadding="10">

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

  1. In Visual Studio, select Debug > Start Debugging to build and start the app locally for testing and debugging.

  2. In the browser, select Azure Cache for Redis Test on the navigation bar.

  3. 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 the PING and CLIENT LIST commands.

    Simple test completed local

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

  1. In Visual Studio, right-click the project node in Solution Explorer. Then select Publish.


  2. Select Microsoft Azure App Service, select Create New, and then select Publish.

    Publish to App Service

  3. 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.

    App Service dialog box

  4. After you configure the App Service hosting settings, select Create.

  5. 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:

    Publishing output

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

  1. Type the app name in the search bar at the top of the Azure portal to find the new app you created.

    Find app

  2. Add a new app setting named CacheConnection for the app to use to connect to the cache. Use the same value you configured for CacheConnection in your CacheSecrets.config file. The value contains the cache host name and access key.

    Add app setting

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.

Simple test completed Azure

Clean up resources

If you're continuing to the next tutorial, you can keep the resources that you created in this quickstart and reuse them.

Otherwise, if you're finished with the quickstart sample application, you can delete the Azure resources that you created in this quickstart to avoid charges.


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 for hosting this sample inside an existing resource group that contains resources you want to keep, you can delete each resource individually from their respective blades instead of deleting the resource group.

To delete a resource group

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

  2. In the Filter by name... box, type the name of your resource group. The instructions for this article used a resource group named TestResources. On your resource group, in the results list, select ..., and then 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.

Next steps

In the next tutorial, you use Azure Cache for Redis in a more realistic scenario to improve performance of an app. You update this application to cache leaderboard results using the cache-aside pattern with ASP.NET and a database.