ASP.NET WEB API-2

Introduction

In my previous article, I have described the situations to use ASP.NET WEB API. This article demonstrates how to create ASP.NET WEB API in Visual Studio 2015 with .NET Framework 4.5. This demonstration creates an ASP.NET WEB API to broadcaste list of student name and creates one HTML client for fectching data.

Getting Started

Developing asp.net web api is very easy as compare to wcf service, it's pattern is same as mvc patter but little difference that it does not contains view, if you know mvc then it will be very easy to under stand and if you dont know mvc, you need not to worry because web api is very is to understand and develope.

Before starting the creation of Web API, I am going to describe the flow of Web API demonstrations. This Web API contains two function
GetAllStudents (Lists Name of students)and GeStudent (Helps to search student name. Below is the code of Web API which we going to demonstrates.

 using MyFirstWebAPI.Models;  
 using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Net;  
 using System.Net.Http;  
 using System.Web.Http;  
 namespace MyFirstWebAPI.Controllers  
 {  
   public class StudentController : ApiController  
   {  
     Student[] students = new Student[]  
     {  
       new Student() { ID = 1, Name = "Kailash"},  
       new Student() { ID = 2, Name = "Ravi" },  
       new Student() { ID = 3, Name = "Kishan",}  
     };  
     public IEnumerable<Student> GetAllStudents()  
     {  
       return this.students;  
     }  
     public IHttpActionResult GeStudent(int id)  
     {  
       var student = this.students.FirstOrDefault((p) => p.ID == id);  
       if (student == null)  
       {  
         return NotFound();  
       }  
       return Ok(student);  
     }  
   }  
 }  

Note that like WCF service, Web API doent require interface to enable functions to access over internet and endpoints (Address,Binding,Contract) for client communication. Just doing followup of rounting pattern you can directly acces Web API function.




Creating Project

Lets start to create Web API, Start Visual Studio and select New Project from the Start Page. Or, from the File Menu, select New=>Project sub menu.In the Templates Pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET Web Application. Name the project "MyFirstWebAPI" and click OK.

In the New ASP.NET Project dialog, select the Empty Template. Under "Add folders and core references for", check Web API. Click OK.

With the completion of above activities, now we are able to create ASP.NET WEB API, you will get details(controllers, models etc.) as in the image

To flow data ASP.NET WEB API uses Modes, a model is an object that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most clients can parse either XML or JSON. Moreover, the client can indicate which format it wants by setting the Accept header in the HTTP request message.

Adding Model

In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class.Name the class "Student". Add the following properties to the Student class like in the code.

 namespace MyFirstWebAPI.Models  
 {  
   public class Student  
   {  
     public int ID { get; set; }  
     public string Name { get; set; }  
   }  
 }  

To make access of your functions of service, there is need to inherit controller If you have used ASP.NET MVC, you are already familiar with controllers. Web API controllers are similar to MVC controllers, but inherit the ApiController class instead of the Controller class.a controller is an object that handles HTTP requests.

Adding Controller

In Solution Explorer, right-click the Controllers folder. Select Add and then select Controller=>In the Add Scaffold dialog, select Web API Controller2 - Empty. Click Add. Because Web API Controller2 - Empty available in Visual Studio 2015.In the Add Controller dialog, name the controller "StudentController". Click Add.

The scaffolding creates a file named StudentController.cs in the Controllers folder.You don't need to put your contollers into a folder named Controllers. Open the StudentController.cs writedown logic for fetching data like below give code example or you may copy the code

 public class StudentController : ApiController  
   {  
     Student[] students = new Student[]  
     {  
       new Student() { ID = 1, Name = "Kailash"},  
       new Student() { ID = 2, Name = "Ravi" },  
       new Student() { ID = 3, Name = "Kishan",}  
     };  
     public IEnumerable<Student> GetAllStudents()  
     {  
       return this.students;  
     }  
     public IHttpActionResult GeStudent(int id)  
     {  
       var student = this.students.FirstOrDefault((p) => p.ID == id);  
       if (student == null)  
       {  
         return NotFound();  
       }  
       return Ok(student);  
     }  
   }  

In the above code example thew controller has two methods, GetAllStudents and GeStudent. The first method returns list of student names from a class array variable students and does not have any parameters, hence the URI of this method will be /api/GetAllStudents and the second method has one parameter called id, hence so the URI of this method will be /api/GeStudent/id. In the URI id is place holder for example, to get the student with ID of 1 then URI will be /api/GeStudent/1
This URI pattern is decided by routing. In the App_Start folder you will find a class 'WebApiConfig', where routing are defined.

  public static class WebApiConfig  
   {  
     public static void Register(HttpConfiguration config)  
     {  
       // Web API configuration and services  
       // Web API routes  
       config.MapHttpAttributeRoutes();  
       config.Routes.MapHttpRoute(  
         name: "DefaultApi",  
         routeTemplate: "api/{controller}/{id}",  
         defaults: new { id = RouteParameter.Optional }  
       );  
     }  
   }  

Our ASP.NET WEB API is ready for consumption, now we will create a json client with the helpf of HTML clent. This HTML displays list of name by fectching from ASP.NET WEB API with the help of Javascript and jQuery.

Adding HTML client

In Solution Explorer, right-click the project and select Add, then select New Item=>In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page "StudentDetails.html".I am not going to explain how to show data in HTML page, just replace the follwoing below code. By right clicking on the StudentDetails.html file make it startup page.

 <!DOCTYPE html>  
 <html>  
 <head>  
   <title>Student Details</title>  
      <meta charset="utf-8" />  
   <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>  
   <script>  
     var uri = 'api/Student';  
   $(document).ready(function () {  
    // Send an AJAX request  
    $.getJSON(uri)  
      .done(function (data) {  
       // On success, 'data' contains a list of products.  
       $.each(data, function (key, item) {  
        // Add a list item for the product.  
         $('<li>', { text: formatItem(item) }).appendTo($('#students'));  
       });  
      });  
   });  
   function formatItem(item) {  
    return item.Name + ':' + item.ID;  
   }  
   function find() {  
    var id = $('#stId').val();  
    $.getJSON(uri + '/' + id)  
      .done(function (data) {  
        $('#student').text(formatItem(data));  
      })  
      .fail(function (jqXHR, textStatus, err) {  
        $('#student').text('Error: ' + err);  
      });  
   }  
   </script>  
 </head>  
 <body>  
   <div>  
   <h2>All Sutdents</h2>  
   <ul id="students" />  
   </div>  
   <div>  
     <h2>Search by ID</h2>  
     <input type="text" id="stId" size="5" />  
     <input type="button" value="Search" onclick="find();" />  
     <p id="student" />  
   </div>  
 </body>  
 </html>  

In the above code example you will find below java script code that send an HTTP GET request to "/api/Student" for getting list of student names on page load event with the JQuery getJSON function. The jQuery getJSON function sends an AJAX request. For response contains array of JSON objects. The done function specifies a callback that is called if the request succeeds. In the callback, we update the DOM with the product information.

 $(document).ready(function () {  
    // Send an AJAX request  
    $.getJSON(uri)  
      .done(function (data) {  
       // On success, 'data' contains a list of products.  
       $.each(data, function (key, item) {  
        // Add a list item for the product.  
         $('<li>', { text: formatItem(item) }).appendTo($('#students'));  
       });  
      });  
   });  

similarly you find another JQuery code that helps search name of student with the ID, Now run you application we will get result like below image.

Related Articles

  1. Difference Between DataContractSerializer and XMLSerializer
  2. Getting Client's IP Address in WCF Service
  3. Consuming Restful API with Bearer Token Authentication using HttpWebRequest
  4. ASP.NET WEB API-1
  5. Difference between WCF And Web Service

Summary

In this article we demonstrated how to create ASP.NET WEB API and how to call ASP.NET WEB API, hope this artcile may helpful to you.

Thanks

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

نموذج الاتصال