MVC 11 Web Api
MVC 11 Web Api
MVC 11 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 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.
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.
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.
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
<script>
</script>
</body>
</html>
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.
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 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" ]
}
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.
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.
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. }
$(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>");
.........
});
}
});
});
Enter the name as “UserModel.cs” and then click on the Add button.
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. }
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. }
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. }
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>