Create And Publish ASP.NET WEB API In Azure

In this article, you will learn how to create and publish ASP.NET Web API Application in Azure.

Introduction

This article will give you step by step instructions of creating an ASP.NET Web API service, using Entity framework, and publishing it in Azure.

Prerequisites

Basic knowledge of ASP.NET Web API, Entity Framework, Kendo UI Framework, and Azure Web apps.

Create an SQL Database in Azure

Let's start with creating a database in Azure. Please check here how to create new database in Azure.

I have created a new database in Azure. Connect the database in SSMS (SQL Studio Management Service), as shown in the image below.

Database
 
The script for creating a table is given below.
  1. CREATE TABLE Employee    
  2.   (    
  3.   EmployeeID INT IDENTITY(1,1) CONSTRAINT Pk_Emp_Id PRIMARY KEY,    
  4.   FirstName VARCHAR(20),    
  5.   LastName VARCHAR(20)    
  6.   )  

Insert some sample record, as shown below.

  1. INSERT INTO Employee VALUES('Bob','Ross')    
  2. INSERT INTO Employee VALUES('Pradeep','Raj')    
  3. INSERT INTO Employee VALUES('Arun','Kumar')    
  4. INSERT INTO Employee VALUES('Vasanth','Kumar')     

Create a new ASP.NET Web API application

Create a new ASP.NET Web API Application, as per the following figures. Open Visual Studio ->File ->New project ->ASP.NET Web Application.

New project 

web api
 
Make sure, the host in Cloud is checked and click OK.

cloud
 
Once Azure Web app settings are configured, click OK.
 
Let us start creating a Model in the application. 

Generate the Model

Now, we will create Entity Framework Models from the database tables.

Step 1 - Right-click the Models folder, select Add, and New Item.

Step 2 - In the Add New Items window, select data in the left pane and ADO.NET Entity Data Model from the center pane. Name the new Model file as Employee and click Add.

Step 3 - In the Entity Data Model wizard, select EF Designer from the database and click Next.

Entity Data Model

Step 4 - Click New Connection button.

Step 5 - In Connection Properties window, provide the name of the Azure SQL Server where the database was created. After providing the Server name, select Employee from the available databases and click OK.

Connection

Step 6 - You can use the default name for connection to save in the Web.Config file and click Next.

Step 7 - Select the table to generate models for Employee table and click Finish.

Create a Controller

Create a new empty Controller. Right-click the Controllers folder and select Add –> New Empty Web API 2 Controller. In my case, I named it as EmployeeCRUD Controller.

Write the code, given below, in the Controller file.

  1. public class EmployeesController : ApiController  
  2.     {  
  3.         private EmployeeEntities db = new EmployeeEntities();  
  4.   
  5.         // GET: api/Employees  
  6.         public IQueryable<Employee> GetEmployees()  
  7.         {  
  8.             return db.Employees;  
  9.         }  
  10.   
  11.           
  12.           
  13.         // PUT: api/Employees/5  
  14.           
  15.         public HttpResponseMessage PutEmployee(Employee employee)  
  16.         {  
  17.             if (!ModelState.IsValid)  
  18.             {  
  19.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);  
  20.             }  
  21.   
  22.   
  23.             db.Entry(employee).State = EntityState.Modified;  
  24.   
  25.             try  
  26.             {  
  27.                 db.SaveChanges();  
  28.             }  
  29.             catch (DbUpdateConcurrencyException ex)  
  30.             {  
  31.                 return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);  
  32.             }  
  33.   
  34.             return Request.CreateResponse(HttpStatusCode.OK);  
  35.         }  
  36.   
  37.         // POST: api/Employees  
  38.           
  39.         public HttpResponseMessage PostEmployee(Employee employee)  
  40.         {  
  41.             if (!ModelState.IsValid)  
  42.             {  
  43.                 db.Employees.Add(employee);  
  44.                 db.SaveChanges();  
  45.                 HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, employee);  
  46.                 response.Headers.Location = new Uri(Url.Link("DefaultApi"new { id = employee.EmployeeID }));  
  47.                 return response;  
  48.             }  
  49.             else  
  50.             {  
  51.                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);  
  52.             }  
  53.               
  54.         }  
  55.   
  56.         // DELETE: api/Employees/5  
  57.           
  58.         public HttpResponseMessage DeleteEmployee(Employee employee)  
  59.         {  
  60.             Employee remove_employee = db.Employees.Find(employee.EmployeeID);  
  61.             if (remove_employee == null)  
  62.             {  
  63.                 return Request.CreateResponse(HttpStatusCode.NotFound);  
  64.             }  
  65.   
  66.             db.Employees.Remove(remove_employee);  
  67.             try  
  68.             {  
  69.                 db.SaveChanges();  
  70.             }  
  71.             catch (DbUpdateConcurrencyException ex)  
  72.             {  
  73.                 return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);  
  74.             }  
  75.   
  76.             return Request.CreateResponse(HttpStatusCode.OK);  
  77.         }  
  78.   
  79.         protected override void Dispose(bool disposing)  
  80.         {  
  81.             if (disposing)  
  82.             {  
  83.                 db.Dispose();  
  84.             }  
  85.             base.Dispose(disposing);  
  86.         }  
  87.   
  88.         private bool EmployeeExists(int id)  
  89.         {  
  90.             return db.Employees.Count(e => e.EmployeeID == id) > 0;  
  91.         }  
  92.     }  
Create a new HTML page in the project where we implemented Kendo Grid with the CRUD operation, to test the REST API Service after publishing the Application.
 
EmployeeGrid.html
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.common.min.css" />  
  5.     <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.default.min.css" />  
  6.     <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.dataviz.min.css" />  
  7.     <link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.dataviz.default.min.css" />  
  8.     <script src="http://cdn.kendostatic.com/2014.3.1316/js/jquery.min.js"></script>  
  9.     <script src="http://cdn.kendostatic.com/2014.3.1316/js/kendo.all.min.js"></script>  
  10.     <title></title>  
  11. </head>  
  12. <body>  
  13.     <script>  
  14.   
  15.       $(document).ready(function () {  
  16.       dataSource = new kendo.data.DataSource({  
  17.       transport: {  
  18.          read:  
  19.          {  
  20.              url: "/api/Employees",  
  21.             dataType: "json",  
  22.          },  
  23.          destroy:  
  24.          {  
  25.              url: "/api/Employees",  
  26.             type: "DELETE"  
  27.          },  
  28.          create:  
  29.          {  
  30.              url: "api/Employees",  
  31.             type:"POST"  
  32.          },  
  33.          update:  
  34.          {  
  35.              url: "api/Employees",  
  36.             type: "PUT",  
  37.             parameterMap: function (options, operation) {  
  38.                if (operation !== "read" && options.models) {  
  39.                   return {  
  40.                      models: kendo.stringify(options.models)  
  41.                   };  
  42.                }  
  43.             }  
  44.          },  
  45.       },  
  46.       schema:  
  47.       {  
  48.          model:  
  49.          {  
  50.             id: "EmployeeID",  
  51.             fields: {  
  52.                 EmployeeID: { editable: false, nullable: true, type: "number" },  
  53.                FirstName: { editable: true, nullable: true, type: "string" },  
  54.                LastName: { editable: true, nullable: true, type: "string" },  
  55.             }  
  56.          }  
  57.       }  
  58.    });  
  59.    $("#grid1").kendoGrid({  
  60.       dataSource:dataSource,  
  61.       editable: "inline",  
  62.       toolbar: ["create"],  
  63.       columns: [  
  64.       {  
  65.          field: "EmployeeID",  
  66.          title: "Employee ID",  
  67.       },  
  68.       {  
  69.          field: "FirstName",  
  70.          title: "First Name"  
  71.       },  
  72.       {  
  73.           field: "LastName",  
  74.           title:"Last Name"  
  75.       },  
  76.       {  
  77.          command: ["edit",  
  78.          {  
  79.             name: "destroy",  
  80.             text: "remove",  
  81.          }  
  82.          ],  
  83.       }  
  84.       ],  
  85.       height: "500px",  
  86.       pageable: {  
  87.          refresh: true,  
  88.          pageSizes: true,  
  89.          buttonCount: 5  
  90.       },  
  91.    }).data("kendoGrid");  
  92. });  
  93.   
  94.     </script>  
  95.     <div class="main-content">  
  96.         <div id="grid1"></div>  
  97.     </div>  
  98. </body>  
  99. </html>       
Now, it’s time to publish the app.

solution explorer

 
Right click on the project in Solution Explorer and click Publish.
 
web app
 
Select recently created Web app for the Application and click OK. 

Check the ApplicationDbContext and EmployeeEntities and click Next.
 
ApplicationDbContext
 
Click Publish to start the process.
  
Once the publishing is completed, just test the REST API Service, using Fiddler/PostMan.
 
Testing the GET service
 
URL: myapi5942.azurewebsites.net/api/Employees 
 
Response

Response 
  
Test the CRUD operation in Kendo Grid, using the Services, which are published in Azure.
 
GET
 
URL: myapi5942.azurewebsites.net/api/Employees
 
Type:GET 

GET  
CREATE
 
URL: myapi5942.azurewebsites.net/api/Employees  
 
Type:  POST
 
POST
DELETE:
 
URL: myapi5942.azurewebsites.net/api/Employees  
 
Type: Delete 
 
Delete
 
 UPDATE:
 
URL: myapi5942.azurewebsites.net/api/Employees
 
Type: PUT 
 
PUT
 
Conclusion

We have seen how to create ASP.NET Web API in Azure App Service and we went through the quick demo of CRUD operation in Kendo Grid which consumes the REST API services that we have created and deployed as Azure Web app.

I hope, you enjoyed this article. Your valuable feedback, questions, or comments about this article are always welcome.