What is WebApi ?
The term API stands for Application Programming Interface.
ASP.NET Web API is a framework which uses HTTP services and that is consumed by various clients. In web Api we can return data on the client requests. As, if we are requesting the data into JSON or XML, we have to define the datatype.
By using the WebAPI we can build pure HTTP based services where the request and response happens with HTTP protocol. Here we can make GET, PUT, POST, and DELETE request and get the WebAPI response accordingly.
By default the Web API returns data in XML format, and we can also change data in JSON format.
We have to create a class which derives from ApiController. The methods defined in the WebAPI controller map to the HTTP methods.
Like we are creating DemoController class and which derives from ApiController.
public class DemoController : ApiController
{
}
Now we are creating a Action in our DemoController classn name Get().
public class DemoController : ApiController
{
List<int> list = new List<int>();
public List<int> Get()
{
list.Add(10);
list.Add(20);
return list;
}
}
Here below, we can have more then one action. So to determine which action to invoke, the framework uses a routing table in Global.asax.
RouteTable.Routes.MapHttpRoute(
name:"DemoAPI",
routeTemplate:"api/{controller}/{action}"
);
Now we are going to use this Get function from our Client page.
So We have to create a Client.html page, and from where we call our api.
here i am using Anguler.js to call my api.
Firstly i have to include below file in client.html page.
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.js"></script>
<body ng-controller="MyController">
<script>
var app = angular.module('MyApp', []);
app.controller('MyController', function ($http) {
$http({
method: 'Get',
url: 'http://localhost:65029/api/Demo/Get',
}).success(function () {
alert(' Success full'); //
})
})
</script>
</body>
here i am using method: 'Get' because i want to Get the data from my api.
And we we want to post some data then i am writing here method: 'Post'.
As i am calling this api from same domain. (Created client.html page in same solution.) so i can consume this api successfully.
But if my client belong to some other domain then i have to implement CORS in global.asax file.
Like
var cors = new System.Web.Http.Cors.EnableCorsAttribute("*", "*", "*");
GlobalConfiguration.Configuration.EnableCors(cors);
This API return me the list from Get Action 10,20 in XML format.
If i want in JSON format then i have to mention datatype in script.
like
dataType: 'json'
How webapi independent of System.Web:-
We can host our webapi in console and window app as well as web application.
because webapi just only perform Get data and Post data operation where we don't have to need of any class of system.web
References
http://www.codeproject.com/Articles/549152/Introduction-to-ASP-NET-Web-API
0 Comment(s)