Click Here to Download WebAPIProject_First.zip
ASP.NET Web API is a framework for developing web APIs on top of the .NET Framework. Web API serves data on HTTP. HTTP service is so powerful and compatible with various clients and platform.
Web API uses in Mobile devices, various browsers and in desktop applications to get or post data.
In this project or tutorial, we will use ASP.NET Web API to create a web API that returns a list of customers and depend on parameters we provide. We are getting results direct on browser and also display in web page with use of jQuery.
As we are developing this project in new framework following are the prerequisite:
Following is the requirement :
This example requires Visual Studio with ASP.NET MVC 4.
We can use any following:
This project we developed in Visual Studio 2012.
Here is the step-by-step explanation of how to create Web API Project.
STEP 1 :
Create a Web API Project.
For that you need to Start Visual Studio and select New Project from the File menu, select New and then Project. In the Templates pane, Select Visual C# Template from the Installed Templates. In Visual C# section , select Web and then select ASP.NET MVC 4 Web Application. After that give project name "WebAPIProject_First" and click OK.
You can see this in following screenshot.
After that the New ASP.NET MVC 4 Project dialog appear, In this, you need to select Web API and select view engine "Razor" this is by default appear so no need to change that after that click OK.
You can see this in following screenshot.
STEP 2 :
Add a Model
A model is an object of a user defined class that represents the data in application. ASP.NET Web API automatically serialize model to XML, JSON, or other format, and then write the serialized data into the body of the HTTP response message.
Client can read this serialization format data and deserialize the object because most of clients can parse either XML or JSON value. Client can also set Accept header in the HTTP request message for indicating that which format it wants.
Not we start creating customer model.
Open Solution Explorer. In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class. Add class name "Customer".
You can see this in below image.
Insert following properties in "Customer" class.
STEP 3 :
Add a Controller
A controller is an object that handles HTTP requests. When we create new project, by default it will create two controllers. These controllers are available in "Controllers" folder.
Now you delete ValuesController file and Add a new controller file.
In Solution Explorer, right-click on the Controllers folder. Select Add and then select Controller and give name "CustomersController.cs" file. This will create new controller in "Controllers" Folder.
You can see this in below image.
Set Controller Name :
Now open the "CustomersController.cs" file and write this code.
Here is "CustomersController.cs" file code.
In this example we stored customers in array in the controller class. But, in a live scenario or real application, you can use a database or data source to get records or data.
In this controller we define three methods that return customer data according to parameter pass:
Each method on the controller class maps to a URI.
Up to now our Web API Project is ready to serve data on the base of URI and parameter we specified in URI.
A client able to invoke these methods by sending an HTTP GET request to the URI.
Here is demonstrating how we call this WebAPI URI from the Browser.
You can use any HTTP client to invoke your web API. In fact, you can call it directly from a web browser.
Now you run your project. The ASP.NET Development Server will start. After project run, you can see something like this URL in your browser http//www.localhost:xxxx/, where xxxx is the port number. By default Home page is opened.
Now we invoke the web API.
For example, to get the list of all customers, we use this URL http://localhost:xxxx/api/customers/.
(Replace "xxxx" with the actual port number.)
The result depends on which web browser you are using.
In Internet Explorer we can get jason file, it will prompt you to open or save a "file" named customers. In firefox it will display as XML.
Firefox View :
Internet Explorer View :
The reason for the difference is that Internet Explorer and Firefox send different Accept headers, so the web API sends different content types in the response.
Now try browsing to these URIs:
http://localhost:xxxx/api/customers/1
http://localhost:xxxx/api/customers?designation=hr
The first URL should return the entry with ID equal to 1.
The second URL should return a list of all the customers with Designation equal to "hr".
Output (URL : http://localhost:xxxx/api/customers/1 ) :
Output (URL : http://localhost:xxxx/api/customers?designation=hr ) :
Now it's time for LIVE actions in Web Pages with Javascript and jQuery.
Now we invoke this Web API from our web-page we call this with Javascript and jQuery.
In Solution Explorer, expand the Views folder, and expand the Home folder under that. You can see a file named Index.cshtml.
This Index.cshtml file renders HTML using the Razor view engine. But here we will not use any Razor features in this example.
Now Open this "Index.cshtml" file and delete all contents of this file and add following code in this file.
Full aspx code :
In this code we are using certain javascript code here is explanation for this. To get a list of all customers, send an HTTP GET request to "/api/customers".
We can do this with jQuery code as follows:
We are using get JSON function to send the AJAX request. The response will be an array of JSON objects. The second parameter to getJSON is a callback function that is invoked when the request successfully completes.
Get a Customer By ID :
To get a customer by ID, send an HTTP GET request to "/api/customers/id", where id is the customer ID.
Following is the javascript for that :
Get a Customer By Designation :
To get a customer by designation, send an HTTP GET request to "/api/customers?designation=designation", where designation is the customer designation, i.e. HR, TL, etc. In this GET request we can receive many customers in response so we make html table for that and display on screen.
Following is the javascript for that :
ASP.NET Web API is a framework for developing web APIs on top of the .NET Framework. Web API serves data on HTTP. HTTP service is so powerful and compatible with various clients and platform.
Web API uses in Mobile devices, various browsers and in desktop applications to get or post data.
In this project or tutorial, we will use ASP.NET Web API to create a web API that returns a list of customers and depend on parameters we provide. We are getting results direct on browser and also display in web page with use of jQuery.
As we are developing this project in new framework following are the prerequisite:
Following is the requirement :
This example requires Visual Studio with ASP.NET MVC 4.
We can use any following:
Visual Studio 2012
Visual Studio Express 2012 for Web
Visual Studio 2010 with ASP.NET MVC 4 installed.
Visual Web Developer 2010 Express with ASP.NET MVC 4 installed.
If you are using Visual Studio 2010 or Visual Web Developer 2010 Express, you will need to install ASP.NET MVC 4 separately.
Visual Studio Express 2012 for Web
Visual Studio 2010 with ASP.NET MVC 4 installed.
Visual Web Developer 2010 Express with ASP.NET MVC 4 installed.
If you are using Visual Studio 2010 or Visual Web Developer 2010 Express, you will need to install ASP.NET MVC 4 separately.
This project we developed in Visual Studio 2012.
Here is the step-by-step explanation of how to create Web API Project.
STEP 1 :
Create a Web API Project.
For that you need to Start Visual Studio and select New Project from the File menu, select New and then Project. In the Templates pane, Select Visual C# Template from the Installed Templates. In Visual C# section , select Web and then select ASP.NET MVC 4 Web Application. After that give project name "WebAPIProject_First" and click OK.
You can see this in following screenshot.
(To view original image , click on image) |
After that the New ASP.NET MVC 4 Project dialog appear, In this, you need to select Web API and select view engine "Razor" this is by default appear so no need to change that after that click OK.
You can see this in following screenshot.
(To view original image , click on image) |
STEP 2 :
Add a Model
A model is an object of a user defined class that represents the data in application. ASP.NET Web API automatically serialize model to XML, JSON, or other format, and then write the serialized data into the body of the HTTP response message.
Client can read this serialization format data and deserialize the object because most of clients can parse either XML or JSON value. Client can also set Accept header in the HTTP request message for indicating that which format it wants.
Not we start creating customer model.
Open Solution Explorer. In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class. Add class name "Customer".
You can see this in below image.
(To view original image , click on image) |
Insert following properties in "Customer" class.
namespace WebAPIProject_First.Models { public class Customer { public int Id { get; set; } public string Name { get; set; } public string Designation { get; set; } public decimal Salary { get; set; } } }
STEP 3 :
Add a Controller
A controller is an object that handles HTTP requests. When we create new project, by default it will create two controllers. These controllers are available in "Controllers" folder.
- HomeController is basically ASP.NET MVC controller. It is serving HTML pages for the site, and is not related to Web API.
- ValuesController is a WebAPI controller.
Note :
Controllers in Web API derive from the ApiController class instead of
Controller class. The first major difference is that actions on Web API
controllers do not return views, they return data. After adding
controller, you have to check that does your class derive from
ApiController if not you have to change that to derive from
ApiController.
Now you delete ValuesController file and Add a new controller file.
In Solution Explorer, right-click on the Controllers folder. Select Add and then select Controller and give name "CustomersController.cs" file. This will create new controller in "Controllers" Folder.
You can see this in below image.
(To view original image , click on image) |
Set Controller Name :
(To view original image , click on image) |
Now open the "CustomersController.cs" file and write this code.
Here is "CustomersController.cs" file code.
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using System.Web.Http; using System.Web.Mvc; using WebAPIProject_First.Models; namespace WebAPIProject_First.Controllers { public class CustomersController : ApiController { // // GET: /Customers/ Customer[] customers = new Customer[] { new Customer { Id = 1, Name = "Rajesh", Designation = "Programmer", Salary = 50000 }, new Customer { Id = 2, Name = "Tom", Designation = "HR", Salary = 40000 }, new Customer { Id = 3, Name = "Mukesh", Designation = "HR", Salary = 45000 } , new Customer { Id = 4, Name = "Sachin", Designation = "TL", Salary = 55000 } , new Customer { Id = 5, Name = "Alex", Designation = "PM", Salary = 60000 } }; public IEnumerable<Customer> GetCustomers() { return customers; } public Customer GetCustomerById(int id) { var customer = customers.FirstOrDefault((p) => p.Id == id); if (customer == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return customer; } public IEnumerable<Customer> GetCustomersByDesignation(string designation) { return customers.Where( (p) => string.Equals(p.Designation, designation,StringComparison.OrdinalIgnoreCase)); } //public ActionResult Index() //{ // return View(); //} } }
In this example we stored customers in array in the controller class. But, in a live scenario or real application, you can use a database or data source to get records or data.
In this controller we define three methods that return customer data according to parameter pass:
- GetCustomers method returns the all customers. it's return type is IEnumerable<Customer> type.
- GetCustomerById method return only one customer which having specified customer id.
- GetCustomersByDesignation method returns all customers with a specified designation.
Each method on the controller class maps to a URI.
Up to now our Web API Project is ready to serve data on the base of URI and parameter we specified in URI.
Controller Method | URI |
GetCustomers | /api/customers |
GetCustomerById | /api/customers/id |
GetCustomersByDesignation | /api/customers/?designation=designation |
A client able to invoke these methods by sending an HTTP GET request to the URI.
Here is demonstrating how we call this WebAPI URI from the Browser.
You can use any HTTP client to invoke your web API. In fact, you can call it directly from a web browser.
Now you run your project. The ASP.NET Development Server will start. After project run, you can see something like this URL in your browser http//www.localhost:xxxx/, where xxxx is the port number. By default Home page is opened.
Now we invoke the web API.
For example, to get the list of all customers, we use this URL http://localhost:xxxx/api/customers/.
(Replace "xxxx" with the actual port number.)
The result depends on which web browser you are using.
In Internet Explorer we can get jason file, it will prompt you to open or save a "file" named customers. In firefox it will display as XML.
Firefox View :
(To view original image , click on image) |
Internet Explorer View :
(To view original image , click on image) |
The reason for the difference is that Internet Explorer and Firefox send different Accept headers, so the web API sends different content types in the response.
Now try browsing to these URIs:
http://localhost:xxxx/api/customers/1
http://localhost:xxxx/api/customers?designation=hr
The first URL should return the entry with ID equal to 1.
The second URL should return a list of all the customers with Designation equal to "hr".
Output (URL : http://localhost:xxxx/api/customers/1 ) :
(To view original image , click on image) |
Output (URL : http://localhost:xxxx/api/customers?designation=hr ) :
(To view original image , click on image) |
Now it's time for LIVE actions in Web Pages with Javascript and jQuery.
Now we invoke this Web API from our web-page we call this with Javascript and jQuery.
In Solution Explorer, expand the Views folder, and expand the Home folder under that. You can see a file named Index.cshtml.
(To view original image , click on image) |
This Index.cshtml file renders HTML using the Razor view engine. But here we will not use any Razor features in this example.
Now Open this "Index.cshtml" file and delete all contents of this file and add following code in this file.
Full aspx code :
<!DOCTYPE html> <html lang="en"> <head> <title>ASP.NET Web API</title> <link href="../../Content/Site.css" rel="stylesheet" /> <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { // Send an AJAX request $.getJSON("api/customers/", function (data) { // On success, 'data' contains a list of customers. $.each(data, function (key, val) { var str = val.Name + ': $' + val.Salary; // Add a list item for the customer. $('<li/>', { text: str }) .appendTo($('#customers')); }); }); }); function findById() { var id = $('#custId').val(); $.getJSON("api/customers/" + id, function (data) { var str = data.Name + ': $' + data.Salary; $('#customer').text(str); }) .fail( function (jqXHR, textStatus, err) { $('#customer').text('Error: ' + err); }); } function findByDesignation() { var strDv = $('#designationValue').val(); var strHTML = '<table><tr style=font-weight:bold><td>Name</td><td>Salary</td></tr>' $.getJSON("api/customers?designation=" + strDv, function (data) { $.each(data, function (key, val) { var str = val.Name + ': $' + val.Salary; strHTML = strHTML + '<tr><td>' + val.Name + '</td><td>' + val.Salary + '</td></tr>' }); strHTML = strHTML + '</table>'; $('#customer').html(strHTML); }) .fail( function (jqXHR, textStatus, err) { $('#customer').text('Error: ' + err); }); } </script> </head> <body id="body"> <div class="main-content"> <div> <h1>All Customers</h1> <ul id="customers" /> </div> <div> <label for="custId">ID:</label> <input type="text" id="custId" size="5" /> <input type="button" value="Search" onclick="findById();" /> <br /> <label for="designationValue">Designation:</label> <input type="text" id="designationValue" size="5" /> <input type="button" value="Search" onclick="findByDesignation();" /> <div id="customer" /> <ul id="customersByDesignation" /> </div> </div> </body> </html>
In this code we are using certain javascript code here is explanation for this. To get a list of all customers, send an HTTP GET request to "/api/customers".
We can do this with jQuery code as follows:
$(document).ready(function () { // Send an AJAX request $.getJSON("api/customers/", function (data) { // On success, 'data' contains a list of customers. $.each(data, function (key, val) { var str = val.Name + ': $' + val.Salary; // Add a list item for the customer. $('<li/>', { text: str }) .appendTo($('#customers')); }); }); });
We are using get JSON function to send the AJAX request. The response will be an array of JSON objects. The second parameter to getJSON is a callback function that is invoked when the request successfully completes.
Get a Customer By ID :
To get a customer by ID, send an HTTP GET request to "/api/customers/id", where id is the customer ID.
Following is the javascript for that :
function findById() { var id = $('#custId').val(); $.getJSON("api/customers/" + id, function (data) { var str = data.Name + ': $' + data.Salary; $('#customer').text(str); }) .fail( function (jqXHR, textStatus, err) { $('#customer').text('Error: ' + err); }); }
Get a Customer By Designation :
To get a customer by designation, send an HTTP GET request to "/api/customers?designation=designation", where designation is the customer designation, i.e. HR, TL, etc. In this GET request we can receive many customers in response so we make html table for that and display on screen.
Following is the javascript for that :
function findByDesignation() { var strDv = $('#designationValue').val(); var strHTML = '<table><tr style=font-weight:bold><td>Name</td><td>Salary</td></tr>' $.getJSON("api/customers?designation=" + strDv, function (data) { $.each(data, function (key, val) { var str = val.Name + ': $' + val.Salary; strHTML = strHTML + '<tr><td>' + val.Name + '</td><td>' + val.Salary + '</td></tr>' }); strHTML = strHTML + '</table>'; $('#customer').html(strHTML); }) .fail( function (jqXHR, textStatus, err) { $('#customer').text('Error: ' + err); }); }
Here in this example we can search by id and search by designation and the search result will show below search textbox.
Now we are running project and see the following outputs:
Output (Default Page) :
(To view original image , click on image) |
Output (Search By Id) :
(To view original image , click on image) |
Output (Search By Designation) :
(To view original image , click on image) |
Output (Invalid input in ID field) :
(To view original image , click on image) |
We will give you advance article on Web API in next Web API post.
Note : Give
Us your valuable feedback in comments. Give your suggestions in this
article so we can update our articles according to that.
Valuable Artical to call web api with json...
ReplyDeleteVery nice article!
ReplyDeleteThis article is very useful but I am unable to display anything on the page . I am getting "The webpage cannot be found" error . please help me out
ReplyDeleteHi,
DeleteI think you did not set startup view in config.