Introduction
A Web Service is an interface which is accessible on the network to application programs. Web Services are built using standard Internet technologies. Clients of a web service don’t need to know the implementation of the web service. The only thing the clients of the web service needs to know is the interface of the web service through which they can communicate with the web service. Now Web API is used to create web services in .NET.
Definitions
Web service is a software resource that is URL-addressable which can perform some function/s.
“Web Services are a new breed of Web Applications which are self-contained and self-describing modular applications. They can be published, located and invoked across the web to perform some task that can be anything from simple requests to complicated business processes. Once the web service is deployed, other applications (can be web services) can discover and invoke the deployed service”
Web API in .NET
Web API is used to implement RESTful web services in .NET. It is based on modular, pluggable pipeline model. When the server with Web API receives a request, it is first passed through .net request pipeline which provides the ability to implement your modules if the default functionality is not enough. You can also host your Web API outside the windows server.
Web API uses MVC Controller and Action concepts. The resources can be directly mapped to the controller. It uses .NET routing engine to map URLs to the controllers. APIs are places within ‘/api/’ route which help to separate API and non-API.

Web API Example
Download Web API 2 Demo Project
Create a new empty web application. Add required folders i.e. Model and Controllers.
Model
The model of your application will represent the data. Wen API in .net can automatically serialize Model to JSON or XML and writes the data to HTTP response message. The client can indicate the desired format by setting the Accept header in HTTP request message.
Create the Model of the application.

Add properties to the class.
EmployeeModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebAPIDemo.Models { public class EmployeeModel { public int Id { get; set; } public string Name { get; set; } public string Designation { get; set; } public double Salary { get; set; } } } |
Controller
The Controller handles HTTP requests.
Create a new Web API 2 Controller – Empty.

Rename the controller as required. Your controller will extend ApiController.
Now add a static list of employee data. (you can also load data from the database in the dataset)
1 2 3 4 5 6 7 |
EmployeeModel[] employee = new EmployeeModel[] { new EmployeeModel { Id = 1, Name = "Jhon Doe", Designation = "General Manager", Salary = 3000 }, new EmployeeModel { Id = 2, Name = "David Ryan", Designation = "Manager", Salary = 2000}, new EmployeeModel { Id = 3, Name = "Kate Snow", Designation = "Assistant", Salary = 500 }, new EmployeeModel { Id = 4, Name = "Jhon Smith", Designation = "CEO", Salary = 5000 }, }; |
Implement methods to get all the records in the form of IEnumerable<EmployeeModel> and another method that returns single user against some Id.
Return Complete List
1 2 3 4 |
public IEnumerable<EmployeeModel> GetEmployeeList() { return employee; } |
Async Secure Response for complete records
If you want to read Async Response. i.e. all the employees
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public HttpResponseMessage GetEmployeeList() { //return the list return Request.CreateResponse(HttpStatusCode.OK, employee); } public class ResponseResultExtractor { public T Extract<T>(HttpResponseMessage response) { return response.Content.ReadAsAsync<T>().Result; } } |
1 |
<span class="kwd">var</span><span class="pln"> result </span><span class="pun">=</span> <span class="typ">ResponseResultExtractor</span><span class="pun">.</span><span class="typ">Extract</span><span class="pun"><</span><span class="typ">List</span><span class="pun"><</span><span class="typ">ListItems</span><span class="pun">>>(</span><span class="pln">response</span><span class="pun">);</span> |
Get Single Record Against Id
Search the list and return the record against a specific record Id. i.e. employee Id
1 2 3 4 5 6 7 8 9 |
public IHttpActionResult GetEmployee(int id) { var employe = employee.FirstOrDefault((p) => p.Id == id); if (employe == null) { return NotFound(); } return Ok(employe); } |
EmployeeController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using WebAPIDemo.Models; namespace WebAPIDemo.Controller { public class EmployeeController : ApiController { EmployeeModel[] employee = new EmployeeModel[] { new EmployeeModel { Id = 1, Name = "Jhon Doe", Designation = "General Manager", Salary = 3000 }, new EmployeeModel { Id = 2, Name = "David Ryan", Designation = "Manager", Salary = 2000}, new EmployeeModel { Id = 3, Name = "Kate Snow", Designation = "Assistant", Salary = 500 }, new EmployeeModel { Id = 4, Name = "Jhon Smith", Designation = "CEO", Salary = 5000 }, }; public HttpResponseMessage GetEmployeeList() { //return the list return Request.CreateResponse(HttpStatusCode.OK, employee); } public class ResponseResultExtractor { public T Extract<T>(HttpResponseMessage response) { return response.Content.ReadAsAsync<T>().Result; } } /*public IEnumerable<EmployeeModel> GetEmployeeList() { return employee; }*/ public IHttpActionResult GetEmployee(int id) { var employe = employee.FirstOrDefault((p) => p.Id == id); if (employe == null) { return NotFound(); } return Ok(employe); } } } |
Until now, you have successfully created a Web Service using Web API now you can access your Web API from the browser through localhost.

As well as, you can also get a single employee record.

Web API Return JSON Only
Your Web API can return JSON only if you want. To return only JSON from the web service open App_Start > WebApiConfig.cs and add JSONFormatter.
1 |
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//WebApiConfig.cs public static class WebApiConfig { public static void Register(HttpConfiguration config) { //Add Json Formatter config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml")); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } |
Web API Return JSON and XML Both
Web API can also return both XML and JSON depending upon the request. If you want to return both XML and JSON open Global.asax file. Add XMLFormatter and JSONFormatter.
1 2 |
GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml")); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
//Global.asax public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); //Add XmlFormatter and JsonFormatter GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml")); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); } } } |
Now your Web API can respond to both XML and JSON requests.
- If you want JSON in response, append ?json=true at the end of the URL i.e. http://localhost:25600/api/employee?json=true
- If you want XML in response, append ?xml=true at the end of the URL i.e. http://localhost:25600/api/employee?xml=true
Call Web API with AJAX and jQuery
Add a new web page and create an ordered list to display the list of employees and input field to filter employees with the help of Id.
1 2 3 4 5 6 7 8 9 10 |
<div> <h2>All Employees</h2> <ol id="employee" /> </div> <div> <h2>Search by ID</h2> <input type="text" id="Id" size="5" /> <input type="button" value="Search" onclick="find();" /> <p id="employeefound"/> </div> |
Populate the list from the response of AJAX request, also get a single record when the user clicks on Search button based on Id.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
$(document).ready(function () { // Send an AJAX request $.getJSON(uri).done(function (data) { // On success, 'data' contains a list of employees. $.each(data, function (key, name) { // Add a list item for the employees. $('<li>', { text: formatemployee(name) }).appendTo($('#employee')); }); }); }); function formatemployee(employee) { return employee.Name + ': ' + employee.Designation +": $"+ employee.Salary; } function find() { var id = $('#Id').val(); $.getJSON(uri + '/' + id).done(function (data) { $('#employeefound').text(formatemployee(data)); }).fail(function (jqXHR, textStatus, err) { $('#employeefound').text('Error: ' + err); }); } |
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Employee App</title> </head> <body> <div> <h2>All Employees</h2> <ol id="employee" /> </div> <div> <h2>Search by ID</h2> <input type="text" id="Id" size="5" /> <input type="button" value="Search" onclick="find();" /> <p id="employeefound"/> </div> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script> <script> var uri = 'api/employee'; $(document).ready(function () { // Send an AJAX request $.getJSON(uri) .done(function (data) { // On success, 'data' contains a list of employees. $.each(data, function (key, name) { // Add a list item for the employees. $('<li>', { text: formatemployee(name) }).appendTo($('#employee')); }); }); }); function formatemployee(employee) { return employee.Name + ': ' + employee.Designation +": $"+ employee.Salary; } function find() { var id = $('#Id').val(); $.getJSON(uri + '/' + id) .done(function (data) { $('#employeefound').text(formatemployee(data)); }) .fail(function (jqXHR, textStatus, err) { $('#employeefound').text('Error: ' + err); }); } </script> </body> </html> |
Hope that you like this tutorial. Stay tuned for more upcoming tutorials. Stay Blessed!