快速入门:将 Azure Redis 缓存与 ASP.NET Web 应用配合使用Quickstart: Use Azure Cache for Redis with an ASP.NET web app

在本快速入门中,将使用 Visual Studio 2019 创建一个 ASP.NET Web 应用程序,该应用程序连接到 Azure Redis 缓存以存储和检索缓存中的数据。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. 然后,将该应用部署到 Azure 应用服务。You then deploy the app to Azure App Service.

跳到 GitHub 上的代码Skip to the code on GitHub

如果要直接跳到代码,请参阅 GitHub 上的 ASP.NET 快速入门If you want to skip straight to the code, see the ASP.NET quickstart on GitHub.


创建 Visual Studio 项目Create the Visual Studio project

  1. 打开 Visual Studio,然后选择“文件” > “新建” > “项目”。Open Visual Studio, and then select File > New > Project.

  2. 在“创建新项目”对话框中执行以下步骤:In the Create a new project dialog box, take the following steps:


    a.a. 在搜索框中,输入“C# ASP.NET Web 应用程序”。In the search box, enter C# ASP.NET Web Application.

    b.b. 选择“ASP.NET Web 应用程序(.NET Framework)”。Select ASP.NET Web Application (.NET Framework).

    c.c. 选择“下一步”。Select Next.

  3. 在“项目名称”框中,为项目提供一个名称。In the Project name box, give the project a name. 在此示例中,我们使用了 ContosoTeamStatsFor this example, we used ContosoTeamStats.

  4. 验证是否已选择“.NET Framework 4.6.1”或更高版本。Verify that .NET Framework 4.6.1 or higher is selected.

  5. 选择“创建”。Select Create.

  6. 选择“MVC”作为项目类型。Select MVC as the project type.

  7. 对于“身份验证”设置,请确保指定“不进行身份验证”。 Make sure that No Authentication is specified for the Authentication settings. 默认的“身份验证”设置可能因 Visual Studio 版本而异。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.

  8. 选择“创建”来创建项目。Select Create to create the project.

创建缓存Create a cache

接下来,为应用创建缓存。Next, you create the cache for the app.

  1. 若要创建缓存,请登录到 Azure 门户并选择“创建资源” 。To create a cache, sign in to the Azure portal and select Create a resource.


  2. 在“新建”页上选择“数据库”,然后选择“Azure Cache for Redis”。On the New page, select Databases and then select Azure Cache for Redis.

    在“新建”中,突出显示了“数据库”和“Azure Cache for Redis”。

  3. 在“新建 Redis 缓存”页上配置新缓存的设置。On the New Redis Cache page, configure the settings for your new cache.

    设置Setting 建议的值Suggested value 说明Description
    DNS 名称DNS name 输入任何全局唯一的名称。Enter a globally unique name. 缓存名称必须是包含 1 到 63 个字符的字符串,只能包含数字、字母或连字符。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. 缓存实例的主机名将是 <DNS name>.redis.cache.chinacloudapi.cnYour cache instance's host name will be <DNS name>.redis.cache.chinacloudapi.cn.
    订阅Subscription 单击下拉箭头并选择你的订阅。Drop down and select your subscription. 要在其下创建此新的 Azure Cache for Redis 实例的订阅。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. 有关详细信息,请参阅用于 Redis 的 Azure 缓存概述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. 在基本或标准缓存实例的“高级”选项卡中,如果想要启用非 TLS 端口,请选择启用开关。In the Advanced tab for a basic or standard cache instance, select the enable toggle if you want to enable a non-TLS port. 还可以选择你想使用的 Redis 版本,4 或(预览版)6。You can also select which Redis version you would like use, either 4 or (PREVIEW) 6.

    Redis 版本 4 或 6。

  8. 在高级缓存实例的“高级”选项卡中,配置非 TLS 端口、群集和数据持久性的设置。In the Advanced tab for premium cache instance, configure the settings for non-TLS port, clustering, and data persistence. 还可以选择你想使用的 Redis 版本,4 或(预览版)6。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. 随后你会转到“查看 + 创建”选项卡,Azure 将在此处验证配置。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. 可以在 Azure Cache for Redis 的“概述”页上监视进度。 You can monitor progress on the Azure Cache for Redis Overview page. 如果“状态”显示为“正在运行”,则表示该缓存可供使用。 When Status shows as Running, the cache is ready to use.

从 Azure 门户检索主机名、端口和访问密钥Retrieve host name, ports, and access keys from the Azure portal

若要连接到某个 Azure Cache for Redis 实例,缓存客户端需要该缓存的主机名、端口和密钥。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. 可以从 Azure 门户检索主机名、端口和访问密钥。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 Redis 缓存密钥

  • 若要获取主机名和端口,请在缓存的左侧导航栏中选择“属性”。 To get the host name and ports, from your cache left navigation, select Properties. 主机名的格式为 <DNS 名称>.redis.cache.chinacloudapi.cn 。The host name is of the form <DNS name>.redis.cache.chinacloudapi.cn.

    Azure Redis 缓存属性

编辑 CacheSecrets.config 文件的步骤To edit the CacheSecrets.config file

  1. 在计算机上创建名为 CacheSecrets.config 的文件。将其放到不会连同示例应用程序的源代码一起签入的位置。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. 在本快速入门中,CacheSecrets.config 文件的路径为 C:\AppSecrets\CacheSecrets.configFor this quickstart, the CacheSecrets.config file is located at C:\AppSecrets\CacheSecrets.config.

  2. 编辑 CacheSecrets.config 文件。Edit the CacheSecrets.config file. 然后添加以下内容:Then add the following content:

        <add key="CacheConnection" value="<cache-name>.redis.cache.chinacloudapi.cn,abortConnect=false,ssl=true,allowAdmin=true,password=<access-key>"/>
  3. <cache-name> 替换为缓存主机名。Replace <cache-name> with your cache host name.

  4. <access-key> 替换缓存的主密钥。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.

更新 MVC 应用程序Update the MVC application

在本部分,请对应用程序进行更新,使之支持一个新视图,该视图显示针对 Azure Redis 缓存执行的一项简单测试。In this section, you update the application to support a new view that displays a simple test against Azure Cache for Redis.

使用缓存的应用设置更新 web.config 文件Update the web.config file with an app setting for the cache

在本地运行应用程序时,将使用 CacheSecrets.config 中的信息连接到 Azure Redis 缓存实例。When you run the application locally, the information in CacheSecrets.config is used to connect to your Azure Cache for Redis instance. 稍后请将此应用程序部署到 Azure。Later you deploy this application to Azure. 到时,请在 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.

由于 CacheSecrets.config 文件未连同应用程序一起部署到 Azure,因此,只是在本地测试应用程序时才使用此文件。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.

更新 web.config 文件的步骤To update the web.config file

  1. 在“解决方案资源管理器”中,双击“web.config”文件将其打开。In Solution Explorer, double-click the web.config file to open it.


  2. web.config 文件中找到 <appSetting> 元素。In the web.config file, find the <appSetting> element. 然后添加以下 file 属性。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.

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

ASP.NET 运行时合并了外部文件的内容以及 <appSettings> 元素中的标记。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. 将 Web 应用部署到 Azure 时,不会部署 CacheSecrets.config 文件。When you deploy your web app to Azure, the CacheSecrets.config file isn't deployed.

将应用程序配置为使用 StackExchange.Redis 的步骤To configure the application to use StackExchange.Redis

  1. 若要将应用配置为使用 Visual Studio 的 StackExchange.Redis NuGet 包,请选择“工具”>“NuGet 包管理器”>“包管理器控制台”。To configure the app to use the StackExchange.Redis NuGet package for Visual Studio, select Tools > NuGet Package Manager > Package Manager Console.

  2. Package Manager Console 窗口运行以下命令:Run the following command from the Package Manager Console window:

    Install-Package StackExchange.Redis
  3. NuGet 程序包会为客户端应用程序下载并添加所需的程序集引用,以通过 StackExchange.Azure Redis 缓存客户端访问 Azure Redis 缓存。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. 如果更愿使用强命名版本的 StackExchange.Redis 客户端库,请安装 StackExchange.Redis.StrongName 包。If you prefer to use a strong-named version of the StackExchange.Redis client library, install the StackExchange.Redis.StrongName package.

更新 HomeController 和布局的步骤To update the HomeController and Layout

  1. 在“解决方案资源管理器”中展开“Controllers”文件夹,然后打开“HomeController.cs”文件。 In Solution Explorer, expand the Controllers folder, and then open the HomeController.cs file.

  2. 在该文件的顶部,添加以下 using 语句。Add the following using statements at the top of the file.

    using StackExchange.Redis;
    using System.Configuration;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;
  3. 将以下成员添加到 HomeController 类,使之支持针对新缓存运行某些命令的新 RedisCache 操作。Add the following members 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 = 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...
        // Note that this requires allowAdmin=true in the connection string
        ViewBag.command5 = "CLIENT LIST";
        StringBuilder sb = new StringBuilder();
        var endpoint = (System.Net.DnsEndPoint)GetEndPoints()[0];
        IServer server = GetServer(endpoint.Host, endpoint.Port);
        ClientInfo[] clients = server.ClientList();
        sb.AppendLine("Cache response :");
        foreach (ClientInfo client in clients)
        ViewBag.command5Result = sb.ToString();
        return View();
    private static long lastReconnectTicks = DateTimeOffset.MinValue.UtcTicks;
    private static DateTimeOffset firstErrorTime = DateTimeOffset.MinValue;
    private static DateTimeOffset previousErrorTime = DateTimeOffset.MinValue;
    private static readonly object reconnectLock = new object();
    // In general, let StackExchange.Redis handle most reconnects,
    // so limit the frequency of how often ForceReconnect() will
    // actually reconnect.
    public static TimeSpan ReconnectMinFrequency => TimeSpan.FromSeconds(60);
    // If errors continue for longer than the below threshold, then the
    // multiplexer seems to not be reconnecting, so ForceReconnect() will
    // re-create the multiplexer.
    public static TimeSpan ReconnectErrorThreshold => TimeSpan.FromSeconds(30);
    public static int RetryMaxAttempts => 5;
    private static Lazy<ConnectionMultiplexer> lazyConnection = CreateConnection();
    public static ConnectionMultiplexer Connection
            return lazyConnection.Value;
    private static Lazy<ConnectionMultiplexer> CreateConnection()
        return new Lazy<ConnectionMultiplexer>(() =>
            string cacheConnection = ConfigurationManager.AppSettings["CacheConnection"].ToString();
            return ConnectionMultiplexer.Connect(cacheConnection);
    private static void CloseConnection(Lazy<ConnectionMultiplexer> oldConnection)
        if (oldConnection == null)
        catch (Exception)
            // Example error condition: if accessing oldConnection.Value causes a connection attempt and that fails.
    /// <summary>
    /// Force a new ConnectionMultiplexer to be created.
    /// NOTES:
    ///     1. Users of the ConnectionMultiplexer MUST handle ObjectDisposedExceptions, which can now happen as a result of calling ForceReconnect().
    ///     2. Don't call ForceReconnect for Timeouts, just for RedisConnectionExceptions or SocketExceptions.
    ///     3. Call this method every time you see a connection exception. The code will:
    ///         a. wait to reconnect for at least the "ReconnectErrorThreshold" time of repeated errors before actually reconnecting
    ///         b. not reconnect more frequently than configured in "ReconnectMinFrequency"
    /// </summary>
    public static void ForceReconnect()
        var utcNow = DateTimeOffset.UtcNow;
        long previousTicks = Interlocked.Read(ref lastReconnectTicks);
        var previousReconnectTime = new DateTimeOffset(previousTicks, TimeSpan.Zero);
        TimeSpan elapsedSinceLastReconnect = utcNow - previousReconnectTime;
        // If multiple threads call ForceReconnect at the same time, we only want to honor one of them.
        if (elapsedSinceLastReconnect < ReconnectMinFrequency)
        lock (reconnectLock)
            utcNow = DateTimeOffset.UtcNow;
            elapsedSinceLastReconnect = utcNow - previousReconnectTime;
            if (firstErrorTime == DateTimeOffset.MinValue)
                // We haven't seen an error since last reconnect, so set initial values.
                firstErrorTime = utcNow;
                previousErrorTime = utcNow;
            if (elapsedSinceLastReconnect < ReconnectMinFrequency)
                return; // Some other thread made it through the check and the lock, so nothing to do.
            TimeSpan elapsedSinceFirstError = utcNow - firstErrorTime;
            TimeSpan elapsedSinceMostRecentError = utcNow - previousErrorTime;
            bool shouldReconnect =
                elapsedSinceFirstError >= ReconnectErrorThreshold // Make sure we gave the multiplexer enough time to reconnect on its own if it could.
                && elapsedSinceMostRecentError <= ReconnectErrorThreshold; // Make sure we aren't working on stale data (e.g. if there was a gap in errors, don't reconnect yet).
            // Update the previousErrorTime timestamp to be now (e.g. this reconnect request).
            previousErrorTime = utcNow;
            if (!shouldReconnect)
            firstErrorTime = DateTimeOffset.MinValue;
            previousErrorTime = DateTimeOffset.MinValue;
            Lazy<ConnectionMultiplexer> oldConnection = lazyConnection;
            lazyConnection = CreateConnection();
            Interlocked.Exchange(ref lastReconnectTicks, utcNow.UtcTicks);
    // In real applications, consider using a framework such as
    // Polly to make it easier to customize the retry approach.
    private static T BasicRetry<T>(Func<T> func)
        int reconnectRetry = 0;
        int disposedRetry = 0;
        while (true)
                return func();
            catch (Exception ex) when (ex is RedisConnectionException || ex is SocketException)
                if (reconnectRetry > RetryMaxAttempts)
            catch (ObjectDisposedException)
                if (disposedRetry > RetryMaxAttempts)
    public static IDatabase GetDatabase()
        return BasicRetry(() => Connection.GetDatabase());
    public static System.Net.EndPoint[] GetEndPoints()
        return BasicRetry(() => Connection.GetEndPoints());
    public static IServer GetServer(string host, int port)
        return BasicRetry(() => Connection.GetServer(host, port));
  4. 解决方案资源管理器 中,展开“视图” > “共享”文件夹。 In Solution Explorer, expand the Views > Shared folder. 然后打开 _Layout.cshtml 文件。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" })

添加新 RedisCache 视图的步骤To add a new RedisCache view

  1. 在“解决方案资源管理器”中,展开“Views”文件夹,并右键单击“Home”文件夹。 In Solution Explorer, expand the Views folder, and then right-click the Home folder. 选择“添加” > “视图...”。 Choose Add > View....

  2. 在“添加视图”对话框中,输入 RedisCache 作为视图名称。In the Add View dialog box, enter RedisCache for the View Name. 然后选择“添加”。Then select Add.

  3. RedisCache.cshtml 文件中的代码替换为以下代码: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

默认情况下,项目配置为在 IIS Express 本地托管应用,以进行测试和调试。By default, the project is configured to host the app locally in IIS Express for testing and debugging.

在本地运行应用的步骤To run the app locally

  1. 在 Visual Studio 中选择“调试” > “开始调试”,在本地生成并启动用于测试和调试的应用。 In Visual Studio, select Debug > Start Debugging to build and start the app locally for testing and debugging.

  2. 在浏览器中,选择导航栏上的“Azure Redis 缓存测试”。In the browser, select Azure Cache for Redis Test on the navigation bar.

  3. 在下面的示例中,Message 键以前有一个缓存值,该值是在门户中使用 Azure Redis 缓存控制台设置的。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. 应用还执行了 PINGCLIENT LIST 命令。The app also executed the PING and CLIENT LIST commands.


在 Azure 中发布和运行Publish and run in Azure

在本地成功测试应用后,即可将应用部署到 Azure 并在云中运行它。After you successfully test the app locally, you can deploy the app to Azure and run it in the cloud.

将应用发布到 Azure 的步骤To publish the app to Azure

  1. 在 Visual Studio 中右键单击解决方案资源管理器中的项目节点,In Visual Studio, right-click the project node in Solution Explorer. 然后选择“发布”。Then select Publish.


  2. 依次选择“Azure 应用服务”、“新建”、“发布”。 Select Azure App Service, select Create New, and then select Publish.


  3. 在“创建应用服务”对话框中进行以下更改:In the Create App Service dialog box, make the following changes:

    设置Setting 建议的值Recommended value 说明Description
    应用名称App name 使用默认值。Use the default. 应用名称是应用部署到 Azure 时对应的主机名。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 选择自己的 Azure 订阅。Choose your Azure subscription. 将对此订阅收取任何相关的托管费用。This subscription is charged for any related hosting costs. 如果有多个 Azure 订阅,请验证是否选择了所需的订阅。If you have multiple Azure subscriptions, verify that the subscription that you want is selected.
    资源组Resource group 使用在其中创建了此缓存的资源组(例如,TestResourceGroup)。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 选择“新建”,然后创建名为 TestingPlan 的新应用服务计划。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.
    应用服务计划为要运行的 Web 应用定义一组计算资源。An App Service plan defines a set of compute resources for a web app to run with.


  4. 配置应用服务托管设置以后,请选择“创建”。After you configure the App Service hosting settings, select Create.

  5. 监视 Visual Studio 中的“输出”窗口,了解发布状态。Monitor the Output window in Visual Studio to see the publishing status. 发布应用后,系统会记录应用的 URL: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

  1. 在 Azure 门户顶部的搜索栏中键入应用名称,查找刚创建的新应用。Type the app name in the search bar at the top of the Azure portal to find the new app you created.


  2. 为应用添加名为 CacheConnection 的新应用设置,用于连接到缓存。Add a new app setting named CacheConnection for the app to use to connect to the cache. 使用在 CacheSecrets.config 文件中为 CacheConnection 配置的相同值。Use the same value you configured for CacheConnection in your CacheSecrets.config file. 该值包含缓存主机名和访问密钥。The value contains the cache host name and access key.


在 Azure 中运行应用Run the app in Azure

在浏览器中,转到应用的 URL。In your browser, go to the URL for the app. 该 URL 显示在 Visual Studio 输出窗口的发布操作结果中。The URL appears in the results of the publishing operation in the Visual Studio output window. 此外,在 Azure 门户中,所创建应用的概览页上也提供了该 URL。It's also provided in the Azure portal on the overview page of the app you created.

选择导航栏上的“Azure Redis 缓存测试”以测试缓存访问。Select Azure Cache for Redis Test on the navigation bar to test cache access.

对完成的 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.

如果已完成快速入门示例应用程序,可以删除本快速入门中创建的 Azure 资源,以免产生费用。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. 登录到 Azure 门户,然后选择“资源组”。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. 本文的说明使用了名为 TestResources 的资源组。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

下一个教程会在一个更真实的场景中使用 Azure Redis 缓存来改善应用的性能。In the next tutorial, you use Azure Cache for Redis in a more realistic scenario to improve performance of an app. 请更新此应用程序,以便使用 ASP.NET 和数据库的缓存端模式来缓存排行榜结果。You update this application to cache leaderboard results using the cache-aside pattern with ASP.NET and a database.