You are on page 1of 23

Why ASP.NET Web API (Web API)?

ASP.NET Web API is a framework for building HTTP services that can be consumed
by a broad range of clients including browsers, mobiles, iphone and tablets. It is very
similar to ASP.NET MVC since it contains the MVC features such as routing,
controllers, action results, filter, model binders.

, Web API can be used as a stand-alone Web services application.


Today, a web-based application is not enough to reach it's customers. People are very
smart, they are using iphone, mobile, tablets etc. devices in its daily life. These
devices also have a lot of apps for making the life easy. Actually, we are moving from
the web towards apps world.
So, if you like to expose your service data to the browsers and as well as all these
modern devices apps in fast and simple way, you should have an API which is
compatible with browsers and all these devices.
For example twitter,facebook and Google API for the web application and phone
apps.

Web API is the great framework for exposing your data and service to different-
different devices. Moreover Web API is open source
Web API Features
1. Supports convention-based CRUD actions, since it works with HTTP verbs
GET,POST,PUT and DELETE.
2. Responses have an Accept header and HTTP status code.
3. Supports multiple text formats like XML, JSON etc. or you can use your
custom MediaTypeFormatter.
4. May accepts and generates the content which may not be object oriented like
images, PDF files etc.
5. Automatic support for OData. Hence by placing the new [Queryable] attribute
on a controller method that returns IQueryable, clients can use the method for
OData query composition.
6. Supports Self-hosting or IIS Hosting.
7. Supports the ASP.NET MVC features such as routing, controllers, action
results, filter, model binders, IOC container or dependency injection.

ASP.NET Web API uses the full features of HTTP like request/response
headers, caching, versioning, etc. It is also a great platform where you can
create your REST-FUL services. You don’t need to define extra configuration
setting for different devices unlike WCF REST Services.
Note:

I want to clear one misconception that Web API does not replace to WCF.
WCF is still a powerful programming model for creating SOAP based services
which supports a variety of transport protocols like HTTP, TCP, Named Pipes
or MSMQ etc.

Start with First Web API Project


Open Visual Studio (I am using Visual studio 2015) and from the File menu,
select New and then click on the Project. It will open a New Project window.

I am using C#, so from the Installed Templates, choose the Visual C# node
and under Visual C#, select Web. In the list of project templates,
choose ASP.NET Web Application. Give the following name to the project,
"WebApiSampleProject" and click OK. It will open a new ASP.NET Project
dialog where you can select many types of template for the project.
In the new ASP.NET Project dialog, select the Empty template and
check Web API. Click OK.
So, finally you have created a Web API project. It will create a default
structure for the project.
Add a model class

Model represents the data. It is an object of your data. The model contains all
application logic such as business logic, validation logic, data access logic,
etc. Web API can automatically serialize the model data to JSON, XML or
some other format. The serialize data write into the body of HTTP response
message. Client can access the data after de-serialization.

To add new model class, in the Solution Explorer, right click on the Models,
select Add and Class.

It will open a dialog for Add New Item, select Visual C# node and
select Class and give the proper name “Employee” for the model class and
select Add. Modify the code for the model as below:

1. namespace WebApiSampleProject.Models
2. {
3. public class Employee
4. {
5. public int EmployeeId
6. {
7. get;
8. set;
9. }
10. public string EmployeeName
11. {
12. get;
13. set;
14. }
15. public string Address
16. {
17. get;
18. set;
19. }
20. public string Department
21. {
22. get;
23. set;
24. }
25. }
26. }

Add a controller

Web API Controller is responsible for handing all HTTP requests which can
come from browser, mobile device, desktop web application or any other.

In Solution Explorer, right click the Controllers folder and select Add and
then select controller.

Note: Web API controller inherit the ApiController class instead of the
Controller class.
It will open Add Scaffold dialog, select the Web API Controller -
Empty template and click on Add.

In the Add Controller dialog, give a proper name to the controller,


"EmployeeController" and click on Add.

You will see scaffolding creates an “EmployeeController.cs” class inside


the controller folder.

Add two methods in the controller “GetAllEmployees” and


“GetEmployeeDetails” and make dummy data for the Employee. See the
following code:

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Net;
5. using System.Net.Http;
6. using System.Web.Http;
7. using WebApiSampleProject.Models;
8. namespace WebApiSampleProject.Controllers
9. {
10. public class EmployeeController: ApiController
11. {
12. IList < Employee > employees = new List < Em
ployee > ()
13. {
14. new Employee()
15. {
16. EmployeeId = 1, EmployeeName = "
Mukesh Kumar", Address = "New Delhi", Department = "IT"
17. },
18. new Employee()
19. {
20. EmployeeId = 2, EmployeeName = "
Banky Chamber", Address = "London", Department = "HR"
21. },
22. new Employee()
23. {
24. EmployeeId = 3, EmployeeName = "
Rahul Rathor", Address = "Laxmi Nagar", Department = "IT"

25. },
26. new Employee()
27. {
28. EmployeeId = 4, EmployeeName = "
YaduVeer Singh", Address = "Goa", Department = "Sales"
29. },
30. new Employee()
31. {
32. EmployeeId = 5, EmployeeName = "
Manish Sharma", Address = "New Delhi", Department = "HR"

33. },
34. };
35. public IList < Employee > GetAllEmployees()

36. {
37. //Return list of all employees
38. return employees;
39. }
40. public Employee GetEmployeeDetails(int id)
41. {
42. //Return a single employee detail
43. var employee = employees.FirstOrDefault(
e => e.EmployeeId == id);
44. if (employee == null)
45. {
46. throw new HttpResponseException(Requ
est.CreateResponse(HttpStatusCode.NotFound));
47. }
48. return employee;
49. }
50. }
51. }

In the above controller you can see that the method “GetAllEmployees”
return the list of all employees and the method “GetEmployeeDetails” returns
the detail of single employee. See the following chart which shows how
controller use route URL to perform action.

Controller Method Route URI


GetAllEmployees /api/employee
GetEmployeeDetails /api/employee/id

Run the Web API


To see the result, you can just create a client application which will use this
web api or you can just simply press F5 or Ctrl+F5. It will open the browser
with Url like http://localhost:53037/

To get all employees list, you need to make changes in the Url such
ashttp://localhost:53037/api/employee.

To get the details of single employee, you need to pass the employee id in the
Url http://localhost:53037/api/employee/4

JSON vs XML

• JSON: JavaScript Object Notation.


• JSON is a syntax for storing and exchanging data.
• JSON is text, written with JavaScript object notation.
When exchanging data between a browser and a server, the data can only
be text. JSON is text, and we can convert any JavaScript object into
JSON, and send JSON to the server.
Sending Data with json
If you have data stored in a JavaScript object, you can convert the object
into JSON, and send it to a server as follow
Example
<!DOCTYPE html>
<html>
<body>

<h2>Convert a JavaScript object into a JSON string, and send it to


the server.</h2>

<script>

var myObj = { "name":"John", "age":31, "city":"New York" };


var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;

</script>

</body>
</html>

This page send this information to the server


demo_json.php:
John from New York is 31

Receiving Data
If you receive data in JSON format, you can convert it into a JavaScript
object:
Example
var myJSON = '{ "name":"John", "age":31, "city":"New York" }';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
in browser
Convert a string written in JSON format, into a JavaScript object.
John
• Both JSON and XML can be used to receive data from a web
server.

The following JSON and XML examples both defines an employees


object, with an array of 3 employees:
JSON Example
{"employees":[
<employee> { "firstName":"John", "lastName":"Doe" },
{ "firstName":"Anna", "lastName":"Smith" },
{ "firstName":"Peter", "lastName":"Jones" }
]}

IN XML WILL BE
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>

JSON is Like XML Because


• Both JSON and XML are "self describing" (human readable)
• Both JSON and XML are hierarchical (values within values)
• Both JSON and XML can be parsed and used by lots of
programming languages
• Both JSON and XML can be fetched with an XMLHttpRequest

JSON is Unlike XML Because


• JSON doesn't use end tag
• JSON is shorter
• JSON is quicker to read and write
• JSON can use arrays
The biggest difference is:
XML has to be parsed with an XML parser. JSON can be parsed by a
standard JavaScript function.

Why JSON is Better Than XML


XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript object.
For AJAX applications, JSON is faster and easier than XML:
Using XML
• Fetch an XML document
• Use the XML DOM to loop through the document
• Extract values and store in variables
Using JSON
• Fetch a JSON string
• JSON.Parse the JSON string

Valid Data Types


In JSON, values must be one of the following data types:
• a string
• a number
• an object (JSON object)
• an array
• a boolean
• null

JSON Strings
Strings in JSON must be written in double quotes.
Example
{ "name":"John" }

JSON Numbers
Numbers in JSON can be an integer or a floating point.
Example
{ "age":30 }

JSON Objects
Values in JSON can be objects.
Example
{
"employee":{ "name":"John", "age":30, "city":"New York" }
}
Objects as values in JSON must follow the same rules as JSON objects.

JSON Arrays
Values in JSON can be arrays.
Example
{
"employees":[ "John", "Anna", "Peter" ]
}

Arrays in JSON Objects


Arrays can be values of an object property:

Example
{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}





Nested Arrays in JSON Objects
Values in an array can also be another array, or even another JSON
object:

Example
myObj = {
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus","Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}

JSON Booleans
Values in JSON can be true/false.
Example
{ "sale":true }

query two database tables, join the data using a conditional
expression, and write the data to a JSON file.

Application json in asp.net mvc


Simple example :
Step 1 >>Lets the model class as follow :

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5.
6. namespace JsonResultDemo.Models
7. {
8. public class UserModel
9. {
10. public int UserId { get; set; }
11. public string UserName { get; set; }
12. public string Company { get; set; }
13. }
14. }


Step2 Add one method named GetUsers in the JsonDemoController.cs file that will
return the list of sample users.

1. private List<UserModel> GetUsers()


2. {
3. var usersList = new List<UserModel>
4. {
5. new UserModel
6. {
7. UserId = 1,
8. UserName = "Ram",
9. Company = "Mindfire Solutions"
10. },
11. new UserModel
12. {
13. UserId = 1,
14. UserName = "chand",
15. Company = "Mindfire Solutions"
16. },
17. new UserModel
18. {
19. UserId = 1,
20. UserName = "Abc",
21. Company = "Abc Solutions"
22. }
23. };
24.
25. return usersList;
26. }

Step 3: Create one Action Controller method named GetUsersData with the
following code in the JsonDemoController.cs file.
1. /// <summary>
2. /// Get tthe Users data in Json Format
3. /// </summary>
4. /// <returns></returns>
5. public JsonResult GetUsersData()
6. {
7. var users = GetUsers();
8. return Json(users, JsonRequestBehavior.AllowGet);

9. }

Step 4: Run the application with this


URL http://localhost:49568/JsonDemo/GetUsersData then the output looks like the
following.
Display json table using jquery

$(document).ready(function(){

$("#button1").click(function(){
$("#mytable2").hide();

$.ajax({
url:'app.php',
type: "GET",
data: ""
dataType: 'json',
success: function(data){
$.each(data, function(key, value){
$("table #mytable1").append("<tr><td>" +
"ID :" + value.ID +
"Name :"+ value.Name +
"Age :" + value.Age +
"</td><tr>");
.........
});
}
});
});

Step 1: Add a class file “UserModel.cs” like the following.

Click on “Class” and then the displayed link is as the following.

Enter the name as “UserModel.cs” and then click on the Add button.

Step 2: Update the code in UserMode.cs with the following code.

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5.
6. namespace JsonResultDemo.Models
7. {
8. public class UserModel
9. {
10. public int UserId { get; set; }
11. public string UserName { get; set; }
12. public string Company { get; set; }
13. }
14. }

Step 3: Add one method named GetUsers in the JsonDemoController.cs file


that will return the list of sample users.

1. /// <summary>
2. /// Get the Users
3. /// </summary>
4. /// <returns></returns>
5. private List<UserModel> GetUsers()
6. {
7. var usersList = new List<UserModel>
8. {
9. new UserModel
10. {
11. UserId = 1,
12. UserName = "Ram",
13. Company = "Mindfire Solutions"
14. },
15. new UserModel
16. {
17. UserId = 1,
18. UserName = "chand",
19. Company = "Mindfire Solutions"
20. },
21. new UserModel
22. {
23. UserId = 1,
24. UserName = "Abc",
25. Company = "Abc Solutions"
26. }
27. };
28.
29. return usersList;
30. }

Step 4: Create one Action Controller method named GetUsersData with the
following code in the JsonDemoController.cs file.

1. /// <summary>
2. /// Get tthe Users data in Json Format
3. /// </summary>
4. /// <returns></returns>
5. public JsonResult GetUsersData()
6. {
7. var users = GetUsers();
8. return Json(users, JsonRequestBehavior.AllowG
et);
9. }

Step 5: Run the application with this URL


http://localhost:49568/JsonDemo/GetUsersData then the output looks like the
following.

Scenario 3: Create JSON data at the client side and send content to the
controller

In this scenario, you will create JSON data at the client side and then that
data will be sent to the Controller action. The controller action request type is
HttpPost.

Step 1: Create one Action controller method named Sample like the following
in the JsonDemoController.cs file.

1. /// <summary>
2. /// Sample View
3. /// </summary>
4. /// <returns></returns>
5. public ActionResult Sample()
6. {
7. return View();
8. }

Step 2: Create a View file named “Sample.cshtml” by right-clicking on View()


in the Sample action controller method then click on “Add View” in the Sample
action like the following.
By clicking on Add View it opens a popup and deselects the "Use a layout
page" option. It then should look as in the following.

Now, click on the OK button then the sample.cshtml file will be created.

Step 3: Replace it with the following cshtml code in the sample.cshtml file.

1. @{
2. Layout = null;
3. }
4.
5. <!DOCTYPE html>
6.
7. <html>
8. <head>
9. <meta name="viewport" content="width=device-
width" />
10. <title>Create Sample JSON Data and send it t
o controller</title>
11. </head>
12. <body>
13. <div>
14. <label>Create Sample User JSON Data and
send it to controller</label><br/><br />
15. <input type="button" id="btnUpdateUserDe
tail" value="Update User Detail" onclick="UpdateUserDetai
l();"/>
16. </div>
17. </body>
18. </html>
19. <script src="~/Scripts/jquery-
1.10.2.min.js"></script>
20. <script lang="en" type="text/javascript">
21. function UpdateUserDetail() {
22. var usersJson = GetSampleUsersList();
23. var getReportColumnsParams = {
24. "usersJson": usersJson
25. };
26. $.ajax({
27. type: "POST",
28. traditional: true,
29. async: false,
30. cache: false,
31. url: '/JsonDemo/UpdateUsersDetail',
32. context: document.body,
33. data: getReportColumnsParams,
34. success: function (result) {
35. alert(result);
36. },
37. error: function (xhr) {
38. //debugger;
39. console.log(xhr.responseText);
40. alert("Error has occurred..");
41. }
42. });
43. }
44. function GetSampleUsersList() {
45. var userDetails = {};
46. var usersList = [];
47. for (var i = 1; i <= 3; i++) {
48. userDetails["UserId"] = i;
49. userDetails["UserName"] = "User-
" + i;
50. userDetails["Company"] = "Company-
" + i;
51. usersList.push(userDetails);
52. }
53. return JSON.stringify(usersList);
54. }
55. </script>

You might also like