How To Store Data In Azure Table Storage Using Rest API In ASP.NET Core - Part Two

In this article, we are going to see how to store data in Azure tables using Rest API in ASP.NET core. ASP.NET Core is an open source web framework which can be run on Mac, Windows, and Linux. Azure Tables is a NoSQL cloud database, not a relational database. It can store just without any other kind of relations, like foreign keys. Read the previous part of the article before continuing with this one.

Adding a new MVC Razor View

  • Open the Solution Explorer.

    How To Store Data In Azure Table Storage Using Rest API in ASP.NET Core
  • Open Views/Home and right click Home -> Add -> View.

    How To Store Data In Azure Table Storage Using Rest API in ASP.NET Core

Open the Add.cshtml file and replace the code given below. Here, we use strongly-typed synchronous forms because it is easy to maintain the forms in cshtml. HTML helpers like @Html.BeginForm(..) create the <form> tag when rendering the web page and @Html.Textbox(..) creates the <input> tag when rendering the webpage.

  1. @model DemoAzureTableRest.Models.MaterialUsageDetails  
  2.   
  3. <div class="container">  
  4.     <h2>Add New Device</h2>  
  5.   
  6.     @using (Html.BeginForm("Add""Home", FormMethod.Post))  
  7.     {  
  8.         <table>  
  9.             <tr>  
  10.                 <th colspan="2" align="center"></th>  
  11.             </tr>  
  12.             <tr>  
  13.                 <td>Device ID: </td>  
  14.                 <td>  
  15.                     @Html.TextBoxFor(m => m.deviceId)  
  16.                 </td>  
  17.             </tr>  
  18.             <tr>  
  19.                 <td>Furnace: </td>  
  20.                 <td>  
  21.                     @Html.TextBoxFor(m => m.furnace)  
  22.                 </td>  
  23.             </tr>  
  24.   
  25.             <tr>  
  26.                 <td>Material: </td>  
  27.                 <td>  
  28.                     @Html.TextBoxFor(m => m.material)  
  29.                 </td>  
  30.             </tr>  
  31.             <tr>  
  32.                 <td>Weight: </td>  
  33.                 <td>  
  34.                     @Html.TextBoxFor(m => m.weight)  
  35.                 </td>  
  36.             </tr>  
  37.             <tr>  
  38.                 <td></td>  
  39.                 <td><input type="submit" value="Submit" /></td>  
  40.             </tr>  
  41.         </table>  
  42.     }  
  43. </div>  
  44.   
  45.   
  46. @if (ViewBag.Message != null)  
  47. {  
  48.     <script type="text/javascript">  
  49.             window.onload = function () {  
  50.                 alert("@ViewBag.Message");  
  51.             };  
  52.     </script>  
  53. }  
  54.   
  55.   
  56. <style>  
  57.     table {  
  58.         border-spacing: 8px 2px;  
  59.     }  
  60.   
  61.     td {  
  62.         padding: 6px;  
  63.     }  
  64. </style>  

Now, open the Controllers/HomeController.cs and replace the code with the one given below. Here, we will get materialUsageDetails model data and pass it to the AzureTable helper class. Azure Table InsertEntity Method requires a storage name, storage key, table name, and model data so we need to pass the following data while calling the InsertEntity method.

  1. public IActionResult Add(MaterialUsageDetails materialUsageDetails)  
  2.         {  
  3.             string response ="";  
  4.             if (materialUsageDetails.deviceId != null)  
  5.             {  
  6.                 materialUsageDetails.PartitionKey = materialUsageDetails.deviceId;  
  7.                 materialUsageDetails.RowKey = materialUsageDetails.furnace;  
  8.                 response = AzureTables.InsertEntity(StorageName, StorageKey, TableName, JsonConvert.SerializeObject(materialUsageDetails));  
  9.             }  
  10.   
  11.             if (response == null)  
  12.             {  
  13.                 ViewBag.Message = "Saved Successfully";  
  14.   
  15.             }  
  16.   
  17.             return View(materialUsageDetails);  
  18.         }  
And, open the Helpers/AzureTables.cs file and add the below code to it. Here, we will create a new entity in Azure Tables using HttpWebRequest. To create the web request, we need the URI and Headers. The required header is given in getRequestHeader() method, the required parameters are HTTP method name ("POST"), request(Http Request), Storage account(storage account name), access key(storage secret key), resource(table name), jsonData.length(model data length). To write a model JSON data into the request body, we use StreamWriter class and execute the request using request.GetRequestStream().
  1. public static string InsertEntity(string storageAccount, string accessKey, string tableName, string jsonData)    
  2.         {    
  3.             string jsonResponse = "";    
  4.             string host = string.Format(@"https://{0}.table.core.windows.net/", storageAccount);    
  5.     
  6.             string resource = string.Format(@"{0}", tableName);    
  7.             string uri = host + resource;    
  8.     
  9.             // Web request     
  10.             HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);    
  11.     
  12.             request = getRequestHeaders("POST", request, storageAccount, accessKey, resource, jsonData.Length);    
  13.     
  14.             // Write Entity's JSON data into the request body    
  15.             using (var streamWriter = new StreamWriter(request.GetRequestStream()))    
  16.             {    
  17.                 streamWriter.Write(jsonData);    
  18.                 streamWriter.Flush();    
  19.                 streamWriter.Close();    
  20.             }    
  21.     
  22.             // Execute the request    
  23.             try    
  24.             {    
  25.                 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())    
  26.                 {    
  27.                     using (System.IO.StreamReader r = new System.IO.StreamReader(response.GetResponseStream()))    
  28.                     {    
  29.                         jsonResponse = r.ReadToEnd();    
  30.                         // return (int)response.StatusCode;    
  31.                     }    
  32.                 }    
  33.             }    
  34.             catch (WebException ex)    
  35.             {    
  36.                 // get the message from the exception response    
  37.                 using (System.IO.StreamReader sr = new System.IO.StreamReader(ex.Response.GetResponseStream()))    
  38.                 {    
  39.                     jsonResponse = sr.ReadToEnd();    
  40.                     // Log res if required    
  41.                 }    
  42.     
  43.                 // return (int)ex.Status;    
  44.             }    
  45.     
  46.             return jsonResponse;    
  47.         }    
  48.   
  49.   
  50.  public static HttpWebRequest getRequestHeaders(string requestType, HttpWebRequest Newrequest, string storageAccount, string accessKey, string resource, int Length = 0)  
  51.         {  
  52.             HttpWebRequest request = Newrequest;  
  53.   
  54.             switch (requestType.ToUpper())  
  55.             {  
  56.                 case "GET":  
  57.                     request.Method = "GET";  
  58.                     request.ContentType = "application/json";  
  59.                     request.ContentLength = Length;  
  60.                     request.Accept = "application/json;odata=nometadata";  
  61.                     request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture));  
  62.                     request.Headers.Add("x-ms-version""2015-12-11");  
  63.                     request.Headers.Add("Accept-Charset""UTF-8");  
  64.                     request.Headers.Add("MaxDataServiceVersion""3.0;NetFx");  
  65.                     request.Headers.Add("DataServiceVersion""1.0;NetFx");  
  66.                     break;  
  67.                 case "POST":  
  68.                     request.Method = "POST";  
  69.                     request.ContentType = "application/json";  
  70.                     request.ContentLength = Length;  
  71.                     request.Accept = "application/json;odata=nometadata";  
  72.                     request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture));  
  73.                     request.Headers.Add("x-ms-version""2015-04-05");  
  74.                     request.Headers.Add("Accept-Charset""UTF-8");  
  75.                     request.Headers.Add("MaxDataServiceVersion""3.0;NetFx");  
  76.                     request.Headers.Add("DataServiceVersion""1.0;NetFx");  
  77.                     break;  
  78.                 case "PUT":  
  79.                     request.Method = "PUT";  
  80.                     request.ContentLength = Length;  
  81.                     request.ContentType = "application/json";  
  82.                     request.Accept = "application/json;odata=nometadata";  
  83.                     request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture));  
  84.                     request.Headers.Add("x-ms-version""2015-04-05");  
  85.                     request.Headers.Add("If-Match""*");  
  86.                     request.Headers.Add("Accept-Charset""UTF-8");  
  87.                     request.Headers.Add("MaxDataServiceVersion""3.0;NetFx");  
  88.                     request.Headers.Add("DataServiceVersion""1.0;NetFx");  
  89.                     break;  
  90.                 case "DELETE":  
  91.                     request.Method = "DELETE";  
  92.                     request.ContentType = "application/json";  
  93.                     request.Accept = "application/json;odata=nometadata";  
  94.                     request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture));  
  95.                     request.Headers.Add("x-ms-version""2015-04-05");  
  96.                     request.Headers.Add("If-Match""*");  
  97.                     request.Headers.Add("Accept-Charset""UTF-8");  
  98.                     request.Headers.Add("MaxDataServiceVersion""3.0;NetFx");  
  99.                     request.Headers.Add("DataServiceVersion""1.0;NetFx");  
  100.                     break;  
  101.             }  
  102.   
  103.             string sAuthorization = getAuthToken(request, storageAccount, accessKey, resource);  
  104.             request.Headers.Add("Authorization", sAuthorization);  
  105.             return request;  
  106.         }  

That's it. Now, run the web application, go to Debug menu, and click on "Start without Debugging" or press F5. To add a new form, change the URL to https://localhost:44392/Home/Add.

 How To Store Data In Azure Table Storage Using Rest API in ASP.NET Core
Now, fill the form and click the "Submit" button.
 
How To Store Data In Azure Table Storage Using Rest API in ASP.NET Core
 
 How To Store Data In Azure Table Storage Using Rest API in ASP.NET Core
I hope you have learned how to store data in 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.