Monday, June 11, 2012

ASP.Net MVC Web API

Using Web API we can develop richer application for various clients. It allows to expose functionality/data in secure way over HTTP rather than through WCF or SOAP.
Lots of people have already developed applications using web API, examples like Google, Facebook, Twitter & etc.

Create a ASP.Net MVC internet Project.  And add a class called Student.
Add a Web API Controller class - StudentsController. Write action methods like below.
After we run the application we can access the API through the browser. We can request http://localhost:1965/api/students, it'll return back all the students in the database.
This is an API. No html associated with it. So we can use a tool like Fiddler.

By changing the Accept header in the HTTP Request Headers we can have json or xml response back. Web API's default response type is json.
Another feature in Web API is OData  support. To request an OData type of request, that the action method must have IQueryable type of return.
We can request http://localhost:1965/api/students?$filter=FirstName eq 'Dilan'. According to the filters the data will be return back from the action method.

Up to now we were retrieving the data from the data base. Now we are going to update the database.
To call that method, we can use Fiddler. In the request headers, we should add the content-type as json.  And then we can send Student object as json type as follows.
We can add more details to the response by adding custom Http status code, custom headers and etc. To do that, we should make few changes to the post method that we wrote.
In the below image, first line is without customizing the response. And second line is, after we add the HttpResponseMessage. The result type is different. And also if we check the headers, there will be location URL for newly created student.

Those are the major things we should know about the Web API.

If we add another no-argument action, and make a request to http://localhost:1965/api/students, this will give an error - Multiple actions were found that match the request.

Reason for that is, in the default project, routing for the api is configured for the controllers. Not for the actions. So we can configure it for actions as follows.
Then we can request for each specific actions like http://localhost:1965/api/students/Get.

The advantage of Web API is we can call it from any client like, Windows Service, WPF, Metro, iOS, Android and etc. Also we can integrate Web API with jquery, knockout and etc. So it makes really easier to develop richer applications.

No comments:

Post a Comment