Introduction
This article will give you step-by-step instructions for 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 a 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.
The script for creating a table is given below.
CREATE TABLE Employee
(
EmployeeID INT IDENTITY(1,1) CONSTRAINT Pk_Emp_Id PRIMARY KEY,
FirstName VARCHAR(20),
LastName VARCHAR(20)
);
Insert some sample records, as shown below.
INSERT INTO Employee VALUES('Bob','Ross');
INSERT INTO Employee VALUES('Pradeep','Raj');
INSERT INTO Employee VALUES('Arun','Kumar');
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.
Make sure, the host in Cloud is checked and click OK.
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.
Step 4. Click the New Connection button.
Step 5. In the 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.
Step 6. You can use the default name for connection to save on the Web. Config the file and click Next.
Step 7. Select the table to generate models for the 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.
public class EmployeesController : ApiController
{
private EmployeeEntities db = new EmployeeEntities();
// GET: api/Employees
public IQueryable<Employee> GetEmployees()
{
return db.Employees;
}
// PUT: api/Employees/5
public HttpResponseMessage PutEmployee(Employee employee)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
db.Entry(employee).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
// POST: api/Employees
public HttpResponseMessage PostEmployee(Employee employee)
{
if (!ModelState.IsValid)
{
db.Employees.Add(employee);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, employee);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = employee.EmployeeID }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
// DELETE: api/Employees/5
public HttpResponseMessage DeleteEmployee(Employee employee)
{
Employee remove_employee = db.Employees.Find(employee.EmployeeID);
if (remove_employee == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
db.Employees.Remove(remove_employee);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool EmployeeExists(int id)
{
return db.Employees.Count(e => e.EmployeeID == id) > 0;
}
}
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
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.common.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.default.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.dataviz.min.css" />
<link rel="stylesheet" href="http://cdn.kendostatic.com/2014.3.1316/styles/kendo.dataviz.default.min.css" />
<script src="http://cdn.kendostatic.com/2014.3.1316/js/jquery.min.js"></script>
<script src="http://cdn.kendostatic.com/2014.3.1316/js/kendo.all.min.js"></script>
<title></title>
</head>
<body>
<script>
$(document).ready(function () {
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: "/api/Employees",
dataType: "json",
},
destroy: {
url: "/api/Employees",
type: "DELETE"
},
create: {
url: "api/Employees",
type: "POST"
},
update: {
url: "api/Employees",
type: "PUT",
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return {
models: kendo.stringify(options.models)
};
}
}
},
},
schema: {
model: {
id: "EmployeeID",
fields: {
EmployeeID: { editable: false, nullable: true, type: "number" },
FirstName: { editable: true, nullable: true, type: "string" },
LastName: { editable: true, nullable: true, type: "string" },
}
}
}
});
$("#grid1").kendoGrid({
dataSource: dataSource,
editable: "inline",
toolbar: ["create"],
columns: [
{ field: "EmployeeID", title: "Employee ID" },
{ field: "FirstName", title: "First Name" },
{ field: "LastName", title: "Last Name" },
{
command: ["edit",
{
name: "destroy",
text: "remove",
}
],
}
],
height: "500px",
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
}).data("kendoGrid");
});
</script>
<div class="main-content">
<div id="grid1"></div>
</div>
</body>
</html>
Now, it’s time to publish the app.
Right-click on the project in Solution Explorer and click Publish.
Select the recently created Web app for the Application and click OK.
Check the ApplicationDbContext and EmployeeEntities and click Next.
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
Test the CRUD operation in Kendo Grid, using the Services, which are published in Azure.
GET
URL: myapi5942.azurewebsites.net/api/Employees
Type: GET
CREATE
URL: myapi5942.azurewebsites.net/api/Employees
Type: POST
DELETE
URL: myapi5942.azurewebsites.net/api/Employees
Type: Delete
UPDATE
URL: myapi5942.azurewebsites.net/api/Employees
Type: 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.