How To Access Data From Azure Table Storage Using Rest API in ASP.NET Core - Part One

In this article, we are going to see how to access data from Azure table storage using Rest API in ASP.NET core. The ASP.NET core is an open source web framework by Microsoft which can be run on MAC, Windows, and Linux. Azure Tables is a NoSQL cloud database and it is not a relational database. It can store, just without any other kind of relations like foreign keys.

Prerequisite

Before you begin to utilize your ASP.NET Core application, the following must be installed in your system.

  1. .NET Core SDK
  2. Integrated Development Environment (IDE)
Creating ASP.NET Core Application

Here, we will see how to create .NET core 2.1 application, and we will use Visual Studio 2017 to create an ASP.NET Core 2.1 application.

  • Open Visual Studio, Click on File -> New Project.
  • In New Project dialog box expand Visual C# and click Web template. Select ASP.NET Core Web Application.
  • Give an appropriate Name, solution name, location and click OK.

    How To Access Data From Azure Table Storage Using Rest API in ASP.NET Core

  • Then, the other pop up will open as below, Select ASP.NET Core 2.1 and Web Application (Model-View-Controller).

    How To Access Data From Azure Table Storage Using Rest API in ASP.NET Core

  • Click OK to create an ASP.NET Core Web Application as shown below.

    How To Access Data From Azure Table Storage Using Rest API in ASP.NET Core

Get Access Key & Storage account name from Azure Portal

  • Go to the Azure portal, Copy Access Key and Storage account name as shown below

    How To Access Data From Azure Table Storage Using Rest API in ASP.NET Core

Now, open the HomeController.cs and type the below code.

  1. using System.Diagnostics;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using DemoAzureTableRest.Models;  
  4. using DemoAzureTableRest.Helpers;  
  5. using Newtonsoft.Json;  
  6.   
  7. namespace DemoAzureTableRest.Controllers  
  8. {  
  9.     public class HomeController : Controller  
  10.     {  
  11.   
  12.         string StorageName = "Enter your storage name";  
  13.         string StorageKey = "Enter the storage key";  
  14.         string TableName = "CraneMachineMaterialUsage()";  
  15.   
  16.         public IActionResult Index()  
  17.         {  
  18.             string jsonData;  
  19.             AzureTables.GetAllEntity(StorageName, StorageKey, TableName, out jsonData);  
  20.             MaterialUsage materialUsage = JsonConvert.DeserializeObject<MaterialUsage>(jsonData);  
  21.   
  22.             return View(materialUsage);  
  23.         }  
  24.   
  25.      }  
  26. }  
  27.   
Then, create a new class AzureTables.cs file and type the below code.
  1. using System;  
  2. using System.Net;  
  3. using System.Security.Cryptography;  
  4. using System.Text;  
  5.   
  6. namespace DemoAzureTableRest.Helpers  
  7. {  
  8.     public class AzureTables  
  9.     {  
  10.         public static int GetAllEntity(string storageAccount, string accessKey, string resourcePath, out string jsonData)  
  11.         {  
  12.             string uri = @"https://" + storageAccount + ".table.core.windows.net/" + resourcePath;  
  13.   
  14.             // Web request   
  15.             HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);  
  16.   
  17.             int query = resourcePath.IndexOf("?");  
  18.             if (query > 0)  
  19.             {  
  20.                 resourcePath = resourcePath.Substring(0, query);  
  21.             }  
  22.   
  23.             request = getRequestHeaders("GET", request, storageAccount, accessKey, resourcePath);  
  24.   
  25.             // Execute the request  
  26.             try  
  27.             {  
  28.                 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())  
  29.                 {  
  30.                     using (System.IO.StreamReader r = new System.IO.StreamReader(response.GetResponseStream()))  
  31.                     {  
  32.                         jsonData = r.ReadToEnd();  
  33.                         return (int)response.StatusCode;  
  34.                     }  
  35.                 }  
  36.             }  
  37.             catch (WebException ex)  
  38.             {  
  39.                 // get the message from the exception response  
  40.                 using (System.IO.StreamReader sr = new System.IO.StreamReader(ex.Response.GetResponseStream()))  
  41.                 {  
  42.                     jsonData = sr.ReadToEnd();  
  43.                     // Log res if required  
  44.                 }  
  45.   
  46.                 return (int)ex.Status;  
  47.             }  
  48.         }  
  49.   
  50.   
  51.         public static HttpWebRequest getRequestHeaders(string requestType, HttpWebRequest Newrequest, string storageAccount, string accessKey, string resource, int Length = 0)  
  52.         {  
  53.             HttpWebRequest request = Newrequest;  
  54.   
  55.             switch (requestType.ToUpper())  
  56.             {  
  57.                 case "GET":  
  58.                     request.Method = "GET";  
  59.                     request.ContentType = "application/json";  
  60.                     request.ContentLength = Length;  
  61.                     request.Accept = "application/json;odata=nometadata";  
  62.                     request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture));  
  63.                     request.Headers.Add("x-ms-version""2015-04-05");  
  64.                     request.Headers.Add("Accept-Charset""UTF-8");  
  65.                     request.Headers.Add("MaxDataServiceVersion""3.0;NetFx");  
  66.                     request.Headers.Add("DataServiceVersion""1.0;NetFx");  
  67.                     break;  
  68.   
  69.             }  
  70.   
  71.             string sAuthorization = getAuthToken(request, storageAccount, accessKey, resource);  
  72.             request.Headers.Add("Authorization", sAuthorization);  
  73.             return request;  
  74.         }  
  75.   
  76.   
  77.         public static string getAuthToken(HttpWebRequest request, string storageAccount, string accessKey, string resource)  
  78.         {  
  79.             try  
  80.             {  
  81.                 string sAuthTokn = "";  
  82.   
  83.                 string stringToSign = request.Headers["x-ms-date"] + "\n";  
  84.   
  85.                 stringToSign += "/" + storageAccount + "/" + resource;  
  86.   
  87.                 HMACSHA256 hasher = new HMACSHA256(Convert.FromBase64String(accessKey));  
  88.   
  89.                 sAuthTokn = "SharedKeyLite " + storageAccount + ":" + Convert.ToBase64String(hasher.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));  
  90.   
  91.                 return sAuthTokn;  
  92.             }  
  93.             catch (Exception ex)  
  94.             {  
  95.                 throw ex;  
  96.             }  
  97.         }  
  98.     }  
  99. }  

Then, create the model class name called MaterialUsage.cs file.

  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace DemoAzureTableRest.Models  
  5. {  
  6.     public class MaterialUsage  
  7.     {  
  8.         public List<MaterialUsageDetails> Value { getset; }  
  9.     }  
  10.   
  11.     public class MaterialUsageDetails  
  12.     {         
  13.         public string PartitionKey { getset; }  
  14.         public string RowKey { getset; }  
  15.         public DateTime Timestamp { getset; }  
  16.         public string deviceId { getset; }  
  17.         public string messageId { getset; }  
  18.         public string furnace { getset; }  
  19.         public string material { getset; }  
  20.         public DateTime time { getset; }  
  21.         public float weight { getset; }  
  22.         public DateTime DateTime { getset; }  
  23.          
  24.     }  
  25. }  

Then open the Index.cshtml and type the below code,

  1. @{  
  2.     ViewData["Title"] = "Home Page";  
  3. }  
  4.   
  5. @model DemoAzureTableRest.Models.MaterialUsage  
  6.   
  7. <div class="row">  
  8.     <div class="col-md-12">  
  9.         <h2>Azure Tables</h2>  
  10.         <table class="table table-striped">  
  11.         <thead>  
  12.             <tr>  
  13.                 <th>Device Id</th>  
  14.                 <th>Furnace Name</th>  
  15.                 <th>Material Name</th>  
  16.                 <th>Weight</th>  
  17.                 <th>Time</th>  
  18.             </tr>  
  19.         </thead>  
  20.         <tbody>  
  21.             @if (Model.Value != null)  
  22.             {  
  23.                 foreach (var item in Model.Value)  
  24.                 {  
  25.                     <tr>  
  26.                         <td>@item.deviceId</td>  
  27.                         <td>@item.furnace</td>  
  28.                         <td>@item.material</td>  
  29.                         <td>@item.weight</td>  
  30.                         <td>@item.Timestamp</td>  
  31.                     </tr>  
  32.                 }  
  33.             }  
  34.             else  
  35.             {  
  36.                 <tr>  
  37.                     <td>No Data</td>  
  38.                 </tr>  
  39.             }  
  40.         </tbody>  
  41.         </table>       
  42.     </div>    
  43. </div>  

That's it. Now run the web application , go to Debug menu and click on Start without Debugging , or press F5. This will open the browser and display the following result.

How To Access Data From Azure Table Storage Using Rest API in ASP.NET Core
 
I hope you have learned how to access data from Azure table storage using Rest API in an ASP.NET core web application. Feel free to fill up the comment box below if you need any assistance.