Wednesday, November 28, 2012

A big picture of Web API, the new Microsft technology for RESTful services

ASP.NET MVC 4 has a new and very powerful framework for making RESTful web services. If you are familiar with WCF REST API, now is the time to think seriously for a replacement! Web API will retire WCF REST API and is very easy to learn and use.

Web API can be used in almost any HTTP based system for normal CRUD applications but it is not suitable for other applications that need different or custom network protocols. For example Web API is not intended to be used for scenarios like real time messaging.

The good thing is that you will find a very comprehensive and nice series of articles here in Microsoft website:
http://www.asp.net/web-api/overview

By using VS2012 in just a few minutes you can build your first REST service. Calling this type of services is very easy. You may use jQuery to call a URL by Ajax or use your ASP.NET web application to submit request to specific URLs or even use the address bar of your web browser. Like MVC controllers, any parameters sent by these requests will automatically map to a method in your controller that have the similar signature. For example:
http://localhost/api/myservice/product/4 will be mapped automatically to GetProduct(int id) method in your ProductsController. If Web API finds more than a method which matches the same pattern you will get HTTP errors like Error 405.

People who already have used MVC, should pay attention to differences between routing in Web API and MVC. Here you will find good samples to understand routing in Web API. In a project created by VS2012, routing commands will be put in APP_Start\WebApiConfig.cs. This file is totally independent and has no relation to RouteConfig.cs which belongs to MVC routings. URIs of Web API requests start with 'api' which help you to easily distinguish them from MVC requests.

Note: Whenever you expose a service to the real world you need to make sure hackers cannot call sensitive methods. The first step in your Web API controller is to exclude normal methods that actions should not be routed to them by adding a [NonAction] attribute above them:

[NonAction] 
public string GetSensitiveData() { ... }


No comments:

Post a Comment