Consuming Windows Azure Mobile Services REST API from ASP.NET Web API App
Windows Azure Mobile Services lets the developers to use structured storage, user authentication and push notifications to Android, iOS, HTML, Windows Store, or Windows Phone 8 apps by leveraging the Windows Azure Cloud platform. Using with Windows Azure Mobile Services, you can enjoy the scalability power of Cloud to your Mobile apps. In this blog post, I will demonstrate how to persist data on Windows Azure Mobile Services Table from a ASP.NET Web API app by leveraging the Windows Azure Mobile Services REST API, and finally provides a generic type helper class for performing CRUD operations on the Windows Azure Mobile Services Table.
Consuming Windows Azure Mobile Services REST API from a ASP.NET Web API App
Windows Azure Mobile Services provides native API for Android, iOS, HTML, Windows Store, or Windows Phone 8 apps so that you can directly consume the Windows Azure Mobile Services from your native Mobile apps. In this post, we will be consume the Windows Azure Mobile Services from a ASP.NET Web API app. Windows Azure Mobile Services provides REST API so that we can easily consume it form our ASP.NET Web API app. This use case is based on a real world app I have recently worked, where iOS clients are consuming a REST API written in ASP.NET Web API and for some persistence over the REST API, we need to send push notifications to the iOS clients. So we are consuming the Windows Azure Mobile Services REST API from ASP.NET Web API app where we need to send push notifications. In this post, I am directly consuming the REST API from my app instead of using any REST API wrapper for .Net clients so that we can explore the Windows Azure Mobile Services REST API.
A Generic CRUD Helper Class for Windows Azure Mobile Services Table
Let’s create a generic type class for CRUD operations on the Windows Azure Mobile Services Table by consuming the REST API of Windows Azure Mobile Services. This generic type helper class can work with any type of Model object.
- public class MobileServiceRequestHelper<T> where T : class
- {
- private string tableEndpoint;
- private string applicationKey;
- private HttpClient client;
- public MobileServiceRequestHelper(string tableName)
- {
- tableEndpoint = ConfigurationManager
- .AppSettings["TableEndpoint"] + tableName ;
- applicationKey = ConfigurationManager
- .AppSettings["X-ZUMO-APPLICATION"];
- client = new HttpClient();
- client.DefaultRequestHeaders.
- Add("X-ZUMO-APPLICATION", applicationKey);
- client.DefaultRequestHeaders.Accept
- .Add(new MediaTypeWithQualityHeaderValue("application/json"));
- }
- }
We are taking the application key and Mobile Services URI from the web.config table and we will pass the Windows Azure Table name in the constructor method of our generic type helper class.
Insert Operation
The API documentation for Insert record operation available from here. The code block below provides the implementation of HTTP Post for inserting a new record onto Windows Azure Mobile Services Table. We are serializing the model object as JSON format and executing the HTTP request by calling the SendAsync method of HTTPClient class.
- public bool Post(T requestData)
- {
- var obj = JsonConvert.SerializeObject(requestData,
- new JsonSerializerSettings()
- {
- NullValueHandling = NullValueHandling.Ignore
- });
- var request = new HttpRequestMessage(HttpMethod.Post,
- tableEndpoint);
- request.Content = new StringContent(obj, Encoding.UTF8,
- "application/json");
- var data = client.SendAsync(request).Result;
- if (data.IsSuccessStatusCode)
- return true;
- else
- throw new HttpResponseException(data.StatusCode);
- }
Update Operation
The API documentation for Update record operation available from here. The code block below provides the implementation of HTTP Put for updating an existing record onto Windows Azure Mobile Services Table.
- public bool Put(T requestData, int id)
- {
- var request = new HttpRequestMessage(new HttpMethod("PATCH"),
- tableEndpoint + id);
- var obj = JsonConvert.SerializeObject(requestData);
- request.Content = new StringContent(obj, Encoding.UTF8,
- "application/json");
- var data = client.SendAsync(request).Result;
- if (data.IsSuccessStatusCode)
- return true;
- else
- throw new HttpResponseException(data.StatusCode);
- }
Please note that Windows Azure Mobile Services used HTTP Verb “PATCH” for updating an existing record.
Delete Operation
The API documentation for Delete record operation available from here. The code block below provides the implementation of HTTP Delete for deleting an existing record from the Windows Azure Mobile Services Table.
- public void Delete(int id)
- {
- var request = new HttpRequestMessage(HttpMethod.Delete,
- tableEndpoint + id.ToString());
- var data = client.SendAsync(request).Result;
- if (!data.IsSuccessStatusCode)
- throw new HttpResponseException(data.StatusCode);
- }
Query Operation
The API documentation for Query record operation available from here. The code block below provides the implementation of querying all records and filtering with id value from the Windows Azure Mobile Services Table.
- public IEnumerable<T> GetAll()
- {
- var result = client.GetStringAsync(tableEndpoint).Result;
- var data = JsonConvert.DeserializeObject<IEnumerable<T>>(result);
- return data;
- }
- public T Get(int id)
- {
- var result = client.GetStringAsync(tableEndpoint +
- "?$filter=Id eq " + id).Result;
- var data = JsonConvert.DeserializeObject<IEnumerable<T>>(result);
- return data.FirstOrDefault();
- }
Windows Azure Mobile Services supports the Open Data Protocol (OData) so that you can query the data from Windows Azure Mobile Services Table by using the query option parameters provided by the OData.
The complete implementation of the MobileServiceRequestHelper class is available on Gist at https://gist.github.com/shijuvar/5562928
Consuming the REST API from ASP.NET Web API App
In the previous steps, we have created a generic type helper class for executing requests against Windows Azure Mobile Services REST API. The code block below provides the HTTP Post operation of our ASP.NET Web API where we inserting a new record onto Windows Azure Mobile Services table named “tokens”
- public HttpResponseMessage Post(Token token)
- {
- if (ModelState.IsValid)
- {
- var req = new MobileServiceRequestHelper<Token>("tokens");
- var isSuccess = req.Post(token);
- if (isSuccess)
- {
- HttpResponseMessage response = Request.CreateResponse(
- HttpStatusCode.Created, token);
- return response;
- }
- throw new HttpResponseException(HttpStatusCode.BadRequest);
- }
- else
- {
- return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
- }
- }
In the above code block, we are creating an object of MobileServiceRequestHelper with generic type Token and inserting a new record on Windows Azure Mobile Services table “tokens”.