e-Zest members share technology ideas to foster digital transformation.

Introduction to ASP.NET Web API?

Written by Trilok Sharma | Dec 30, 2014 3:34:36 PM

Web API provides you a platform where you can build and consume HTTP services. We can get and post data in XML and JSON format. It is good for mobile and iPad applications that return data in JSON and XML. We go with JSON because JSON is faster than XML. JSON doesn’t have attribute and is good even with a slow internet connection.

Why use ASP.NET Web API?

Web API is a light weight HTTP service because XML, JSON etc media type can be used to get and post data. It is a first-class programming model for HTTP and more suitable for access from various browsers, mobile and iPad devices etc. There is filter through which secure data can be posted and got without any issue. Inversion of Control (IOC) to Web API offers tremendous value because of which ApiControllers become decoupled and no longer have to manage their dependencies.

Asp.Net Web API VS Asp.Net MVC

Asp.Net MVC is used to create web-based applications and have views but Web API does not return any views and is used to create HTTP services.

ASP.NET Web API Routing

Base controller of Asp.Net MVC is Controller and base controller of Web API is API Controller. MVC controller is used for return view and APIController is used for return data in serialized form.

public class HomeController : Controller {

Public class HomeController : ApiController {

When any HTTP request comes, the Controller class handles that HTTP request and map route url that invokes action methods mentioned in controller. There is a default route pattern difference between Asp.Net MVC and Web API.

Default route Pattern for Asp.Net MVC

                               “{controller}/{action}/{id}”.
          Example :   routes.MapRoute(null, "checkpill/terms-and-conditions", new { Controller = "CPill", action = "Index" });

Default route Pattern for Web API

“api/{controller}/{id}”.

Asp.Net Web API VS Asp.Net Web API 2

1. Attribute Routing
We was using default route template in Web API.

Config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{Controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

But In API 2 Added new features Attribute routing. That support above mentioned URI pattern

[Route("Product /{itemId}/Items ")]
public IList<Product> GetProductByItem(int itemId)
 {
  // code
 }

2. CORS - Cross Origin Resource Sharing
3. OWIN
4. IHttpActionResult
5. Web API OData

Benefits
Web API is very good for mobile and iPad apps with a slow internet connection. It offers a fast way to send and receive data.