Creating Asp.net Web Api and Consuming it through HTML Clients

Creating ASP.NET Web API Data Service

Adding an ASP.NET Web API controller to your application is almost exactly like adding an ASP.NET MVC controller. You can either add a web api in the existing MVC project or can create a separate Web Api project.

Let us create a new Web Api project.

Start Visual Studio 2010 and follow the steps below :

  1. Select New Project and choose ASP.NET MVC 4 Web Application from the list of project templates. Name the Project DemoWebApi .
  2. In the Project Template dialog, select Web API and click Ok

webapi

As soon as you click Ok, a default web api project is created. In the controller folder a file named ValuesController.cs is created. This is the default Web API service fie added. Either you can modify this or you can add a new API Controller .

In the Global.asax file a default routing map is also added in the RegisterRoutes function

routes.MapHttpRoute(

name: “DefaultApi”,

routeTemplate: “api/{controller}/{id}”,

defaults: new { id = RouteParameter.Optional }

);

you can make modifications to this file to reflect any configuration changes you want to make for the application. The default contains a single route as an example to get you started.

Let us create our own Employee API Controller instead of modifying the existing ValuesController.cs

Before creating the employeeApi controller we will be creating the Employee model and Employee Manager class which will be used in the Employee API controller to perform CRUD operations .

Model

In Solution Explorer, right-click the Models folder then add the below class named Employee.

public class Employee

{

publicint Id { get; set; }

publicstring Name { get; set; }

publicstring Dept { get; set; }

publicdecimal Salary { get; set; }

}

Now add the following Interface and class in the same Model folder.

interface IEmployeeManager

{

List<Employee> GetAll();

Employee Get(int id);

Employee Add(Employee item);

void Remove(int id);

bool Update(Employee item);

}

public class EmployeeManager:IEmployeeManager

{

List<Employee> employees = newList<Employee>();

privateint _nextId = 1;

public EmployeeManager()

{

Add(newEmployee { Name = “John”, Dept = “HR”, Salary = 1000 });

Add(newEmployee { Name = “David”, Dept = “Accounts”, Salary = 2000 });

Add(newEmployee { Name = “Haris”, Dept = “RnD”, Salary = 3000 });

}

public List<Employee> GetAll()

{

return employees;

}

public Employee Get(int id)

{

var emp = employees.Find(p => p.Id == id);

return emp;

}

public Employee Add(Employee item)

{

if (item == null)

{

throw new ArgumentNullException(“item”);

}

item.Id = _nextId++;

employees.Add(item);

return item;

}

public void Remove(int id)

{

employees.RemoveAll(p => p.Id == id);

}

public bool Update(Employee item)

{

if (item == null)

{

throw new ArgumentNullException(“item”);

}

int index = employees.FindIndex(p => p.Id == item.Id);

if (index == -1)

{

return false;

}

employees.RemoveAt(index);

employees.Add(item);

return true;

}

}

Now we are ready to create our own employee web api controller. Before adding the new api controller delete the file named ValuesController.cs within Controllers folder from the project.

Add a Web API Controller

In Solution Explorer, right-click the Controllers folder. Select Add and then select Controller.

In the Add Controller dailog, name the controller EmployeeController. In the Template drop-down list, select Empty API Controller and click Add.

apicontroller

Add the following code in the EmployeeController.cs class

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net.Http;

using System.Web.Http;

using DemoWebApi.Models;

using System.Net;

namespace DemoWebApi.Controllers

{

public class EmployeeController : ApiController

{

static readonly IEmployeeManager empManager = newEmployeeManager();

//Get All employees

[HttpGet]

public List<Employee> GetAllEmployees()

{

return empManager.GetAll();

}

//Get employee by id

[HttpGet]

public Employee GetEmployeeById(int id)

{

var emp = empManager.Get(id);

if (emp == null)

{

throw new HttpResponseException(HttpStatusCode.OK);

}

return emp;

}

//Add employee

[HttpPost]

public Employee AddEmployee(Employee emp)

{

emp = empManager.Add(emp);

return emp;

}

//Update employee

[HttpPut]

public void UpdateEmployee(Employee emp)

{

if (!empManager.Update(emp))

{

throw new HttpResponseException(HttpStatusCode.NotFound);

}

}

//Delete employee

[HttpDelete]

public void DeleteEmployee(int id)

{

Employee emp = empManager.Get(id);

if (emp == null)

{

throw new HttpResponseException(HttpStatusCode.NotFound);

}

empManager.Remove(id);

}

}

}

Convention over Configuration

Like ASP.NET MVC, ASP.NET Web API makes heavy use of convention over configuration

to lighten the workload involved in creating web data services. For example,

instead of requiring you to annotate each method with an attribute such as HttpPost

Attribute or HHTP Get Attribute( as we have done in the example above) to identify what type of requests an action may handle ApiController methods rely on names that correspond to the standard HTTP actions. For doing so we must prefix the action name with the apprortiate HTTP verbs(GET, POST,PUT and Delete)

For example the

//Add employee

[HttpPost]

public Employee AddEmployee(Employee emp)

{

emp = empManager.Add(emp);

return emp;

}

can be written without the attribute [HttpPost] if we prefix the action with Post like

public Employee PostEmployee(Employee emp)

{

emp = empManager.Add(emp);

return emp;

}

It is important to understand that the controller action naming convention only applies when the name corresponds to one of the standard REST actions (GET, POST, PUT, andDELETE). However, if you like to name your methods differently you can apply the AcceptVerbsAttribute— such as HttpGetAttribute or HttpPostAttribute or HttpPutAttribute or HttpDeleteAttribute as we have done in our example.

Consuming the Web Api Data Service from a HTML client

 Consuming the web api service from html client is very easy. We are going to do that using Jquery. You can download the latest version of Jquery or can use the existing one which is 1.6.2.js

Modify the default index.cshtml in the View/Home folder with the following Markup

to provide a GUI for Displaying Employees and their different actions.

<!DOCTYPEhtml>

<htmllang=”en”>

<body>

<header>

<div>

<h2>Web Api Demo </h2>

</div>

<scripttype=”text/javascript”src=”../../Scripts/jquery-1.6.2.js”></script>

</header>

<divid=”body”>

<sectionclass=”content-wrapper main-content clear-fix”>

<div>

<h3>Employee List</h3>

<inputtype=”button”value=”GetAll”onclick=”GetAllEmployee();”/>

<ulid=”emps”/>

</div>

<div>

<h3>Search by ID</h3>

<inputtype=”text”id=”empId”size=”5″/>

<inputtype=”button”value=”Search”onclick=”FindEmploye();”/>

<pid=”emp”/>

</div>

<div>

<h3>Delete Employee by ID</h3>

<inputtype=”text”id=”delempId”size=”5″/>

<inputtype=”button”value=”Delete”onclick=”DeleteEmploye();”/>

</div>

<div>

<h3>Add Employee </h3>

<table>

<tr>

<td>Name</td><td><inputtype=”text”id=”txtName”/></td>

</tr>

<tr>

<td>Dept</td><td><inputtype=”text”id=”txtDept”/></td>

</tr>

<tr>

<td>Salary</td><td><inputtype=”text”id=”txtSal”/></td>

</tr>

<tr>

<tdcolspan=”3″align=”center”><inputtype=”button”value=”Add”onclick=”AddEmployee();”/></td>

</tr>

</table>

</div>

</section>

</div>

Now add the following Javascript/jquery code to call the web api data service

 <script type=”text/javascript”>

 var rootUrl = “http://” + document.location.hostname + “:” + window.location.port;

var apiUrl = ‘/api/Employee’;

$(document).ready(function () {

});

function GetAllEmployee() {

//$(“#emps”).empty();

$.ajax({

url: rootUrl + apiUrl,

type: ‘GET’,

dataType: ‘json’,

success: function (data) {

DisplayEmployeeList(data);

},

error: function () {

alert(‘Some error occured’);

}

});

}

function formatItem(item) {

return item.Id +” “+ item.Name + ” “+ item.Dept + ‘: $’ + item.Salary;

}

function FindEmploye() {

var id = $(‘#empId’).val();

$.getJSON(apiUrl + ‘/’ + id)

.done(function (data) {

//$(‘#emp’).text(formatItem(data));

ShowEmployeeForEdit(data);

})

.fail(function (jqXHR, textStatus, err) {

$(‘#emp’).text(‘Error: ‘ + err);

});

}

function DeleteEmploye() {

var id = $(‘#delempId’).val();

$.ajax({

url: rootUrl + apiUrl + ‘/’ + id,

type: ‘DELETE’,

dataType: ‘json’,

success: function (data) {

alert(‘Employee deleted’);

GetAllEmployee();

},

error: function () {

alert(‘Employee not found’);

}

});

}

function UpdateEmployee() {

var employee = {

Id: $(‘#empId’).val(),

Name: $(‘#txtEditName’).val(),

Dept: $(‘#txtEditDept’).val(),

Salary: $(‘#txtEditSal’).val()

};

$.ajax({

url: rootUrl + apiUrl,

type: ‘PUT’,

data: JSON.stringify(employee),

contentType: “application/json;charset=utf-8″,

success: function (data) {

alert(‘Employee updated’);

GetAllEmployee();

},

error: function () {

alert(‘Some error occured’);

}

});

}

function AddEmployee() {

var employee = {

Name: $(‘#txtName’).val(),

Dept: $(‘#txtDept’).val(),

Salary: $(‘#txtSal’).val()

};

$.ajax({

url: rootUrl + apiUrl,

type: ‘POST’,

data: JSON.stringify(employee),

contentType: “application/json;charset=utf-8″,

success: function (data) {

alert(‘Employee added’);

GetAllEmployee();

},

error: function () {

alert(‘Some error occured’);

}

});

}

function DisplayEmployeeList(employees) {

$(“#emps”).empty();

var strResult = “<table><th>EmpID</th><th>Name</th><th>Department</th><th>Salary</th>”;

$.each(employees, function (index, employee) {

strResult += “<tr><td>” + employee.Id + “</td><td> “ + employee.Name + “</td><td>” + employee.Dept + “</td><td>” + ‘: $’ + employee.Salary + “</td></tr>”;

});

strResult += “</table>”;

$(“#emps”).html(strResult);

}

function ShowEmployeeForEdit(employee) {

$(“#emp”).empty();

if (employee == null) {

alert(‘Employee Not Found’)

return;

}

$(“#emp”).empty();

var strResult = “<table>”+

“<tr><td>Name</td><td><input type=’text’ id=’txtEditName’ value='” +employee.Name+“‘</td></tr>”+

“<tr><td>Dept</td><td><input type=’text’ id=’txtEditDept’ value='”+ employee.Dept +“‘</td></tr>”+

“<tr><td>Salary</td><td><input type=’text’ id=’txtEditSal’ value='” + employee.Salary + “‘</td></tr>” +

“<tr><td colspan=’3’align=’center’><input type=’button’ value=’Update’ onclick=’UpdateEmployee();’ </td></tr>” +

“</table>”;

$(“#emp”).html(strResult);

}

</script>

 This is all done. We have seen how to create and consume the new asp.net web api data service. You can download the source code from the link below .

Download: DemoWebApi

Leave a Reply

Your email address will not be published. Required fields are marked *


three − = 0

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>