Gold Award WinnerGold Award Winner

Introduction

Microsoft Azure Cache (Redis) is based on open source Redis Cache. And Microsoft created a Platform as a Service (PaaS) around it, which can be provisioned through the Microsoft Azure Portal or PowerShell scripts. The service will give you a secure, and dedicated Redis cache hosted in a Microsoft data center. Data can be stored as key/value pair and access via an API or other means. This article will show how to access data in Redis Cache from an Azure API App.

Scenario

An Azure API App will access data in the Redis Cache. The data will be query by one of the operations of the WebAPI and update data in another operation call. The API App will have two operations one query data (GET) by a parameter and update existing data (POST). The diagram below demonstrates the scenario.

Set up

A Redis Cache will be provisioned and sample data will loaded into the cache. An API App will be built in Visual Studio and be deployed in an API App in Microsoft Azure. The API App will have swagger support, hence we can test the API in a browser locally and once the API App is deployed. Provisioning the Redis Cache is described in the online documentation, see the section create your first Redis.

Prerequisites

To build a solution similar to this one or create API’s yourself that you like to host in Azure than you need an Azure Account and subscription. If you do have access to a subscription than you should be able to connect to it via Visual Studio in the Server Explorer as shown in the picture below.



You will need to install the latest Azure SDK for Visual Studio 2013.

Walkthrough

The Getting Started with ASP.NET Web API 2 is an excellent resource to get you up to speed building a Web API. In a similar fashion the Web API to access Redis Cache data has been built using the ASP.NET Template in Visual Studio 2013.



Notice the Application Insight is not added to the project. You choose to do so if you need to understand and optimize application performance. To keep the focus in this article on communication with Redis we not going to leverage the functionality. More on Application Insight see Visual Studio Application Insight. Once OK has been click the following dialog will appear.



In this dialog we choose Azure API App, as this provide an out of box implementation of swagger (reference to Swashbuckle.Core is included). This saves us time as with Web API template you need to add Swashbuckle yourself and instrument the code. The other reason is we just need the references for the Web API and nothing else. Click OK to proceed and another dialog screen will appear asking us for details for the hosting environment. In the previous screen you can see we choose to Host the API in the cloud in an App Service. Now we need to specify the API App Name, Subscription, Resource Group and Price Plan. The latter can created manually or you can choose an existing one.



The Create will provision a publishing profile in your Visual Studio project.



We will navigate to the App_Start folder and open SwaggerConfig and uncomment the following piece:

    })
.EnableSwaggerUi(c =>
    {

By doing so we now have enabled the swagger UI.

Now we have a base we can start working with, which means we need to add a controller and a model (data) to work with. The model will be a representation of the data that will be obtained from the Redis Cache. It will represent an order with the following format:



{
  "id": "A345",
  "descr": "Microsoft Surface PRO 4 256Gb",
  "number": "12374623874568273648123",
  "amount": "1",
  "date": "15-2-2016"
}

The key is id and value is the complete JSON as represented above. A class will be added to the Models folder and have the following code.

namespace AzureRedisCacheAPI.Models
{
public class Order
    {
        public string id { get; set; }
        public string descr { get; set; }
        public string number { get; set; }
        public string amount { get; set; }
        public string date { get; set; }
    }
}

Next we will add a controller to Controllers folder. When choosing Add à Controller a dialog box will appear as shown in the picture below.



Once the Controller class is created we will add a NuGet package to enable us to communicate with the Redis Cache. In Manage NuGet packages we will look for StackExchange.Redis and install it.



Once the package is installed we will implement the code below into our controller class.



using System;
using System.Web.Http;
using System.Configuration;
using StackExchange.Redis;
using System.Web.Script.Serialization;
 
namespace AzureRedisCacheAPI.Controllers
{
    using Models;
 
    public class OrderController : ApiController
    {
        private static Lazy<ConnectionMultiplexer> lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
        {
            return ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["RedisConnectionString"]);
        });
 
        public static ConnectionMultiplexer Connection
        {
            get
            {
                return lazyConnection.Value;
            }
        }
 
        [HttpGet]
        public Order Get(string id)
        {
            IDatabase cache = Connection.GetDatabase();
 
            string json = cache.StringGet(id);
 
            JavaScriptSerializer j = new JavaScriptSerializer();
            Order order = (Order)j.Deserialize(json, typeof(Order));
 
            return order;
        }
 
        [HttpPost]
        public Order Change(string id,Order order)
        {
            IDatabase cache = Connection.GetDatabase();
 
            JavaScriptSerializer j = new JavaScriptSerializer();
            string json = j.Serialize(order);
 
            try
            {
                cache.StringSet(order.id, json);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
 
            return order;
        }
    }
}




The implementation of the connection to Redis is derived from the How to Use Azure Redis Cache documentation from Microsoft Azure. The Get and Change methods support HTTP GET and POST. The GET will retrieve an order from the Redis with key id and the POST will change using the id. The change will be in the JSON payload.

Testing the solution locally in a browser

Once the project is build it can be started locally in a web browser i.e. one that you specify. In project properties we have specified to use local IIS express using the path (localhost) and random port.



A browser page will appear with HTTP 403 message.



Add /swagger and you will see the swagger UI appear, which will show the operation. We will drill down and examine the operation documentation.



We will fill in an id and click Try it out! We will see a response of the GET /api/Order{id}, where the ID is A345.



We can also test the change i.e. POST. By choosing the same id, A345, and past the payload from the GET into order and change the amount to 4 and click Try it out!



The result will be return in the response with the representation of how the order is stored in the Redis.











Deployment

Now we now the API functions as expected and we can deploy the API to Azure. We close the browser and stop debug of the API. Next we right click the Visual Studio project and choose Publish. A dialog will appear as shown below.



The settings in this screen are from the publishing settings and we can validate if the connection is valid by clicking Validate Connection.



We have a valid connection, subsequently we click Next.



In the above dialog we can change the configuration setting if we want, specify any File Publish Options, which is not required here or specify any database (not present in the project). And finally we can click Next to preview the deployment. Click Preview and examine the output.



We see all the resources are in the deployment, hence we click Publish. And in the output Windows of Visual Studio we see the following in the screenshot below.



Once the deployment is finished a browser window will appear.



We add /swagger to it and have the Swagger UI available again.



Now we can repeat the same test as we did locally.



In the Microsoft Azure Portal we can find out API and look at some of the details.



And through All settings we can examine the API.



Resources

This article scratched the surface around Redis Cache. We implemented a solution having a Web API as a wrapper around the Redis Cache. The following resources will provide more information.

Other aspects around API Apps have not been discussed, yet are equally important such as security, scalability, managing and monitoring. You can look into these aspects online in the API Apps Overview and related links.

See Also

Another important place to find an extensive amount of Microsoft Azure App Service related articles is the TechNet Wiki itself. The best entry point is Microsoft Azure App Service Resources on the TechNet Wiki.