Friday, November 8, 2013

Webapi vs MVC

Webapi is one of the most popular way of achieving RESTful service. It utilizes the HTTP verbs to handle the request and resonse.
Project wise i didnt see much of the difference between these 2. Here are few differences i could figure out -

mvc webapi
Controller inherit from MVC controller controller inhrit from APIController(Http Controller)
Common Routing based upon controller/action Common routing based upon controller/HttpVerb
Controller action returns a view Controller Action returns data
Routing defined by routeconfig class ->MapRoute method Routing defined by webapiconfig class ->MapHttpRoute method
Unlike MVC, Routing API here does not use any reference to MVC

If you see both webAPI and MVC are different from traditional requests. Traditionally the url used to have the extension of the file(like .aspx, .JSP, .ashx). But in this case we dont have any extension.
Hence in order to identify the request and proper routing at IIS level, we need to run the IIS in integrated mode. Which is mainly for .NET requests.

While creating a sample project on webapi i see that routing plays and important role here. But how does this application know that i have to hit the routing and then execute the code in corresponding controller.
Well as per my understanding and from few documentation from MSDN, i found that there is one httpmodule(named as URLRoutingModule) plays an important role. It actually captures data from the request(like HTTPContext etc) and using the routingHandler(MVCRouteHandler) it get the instance of MVCHandler. MVCHandler is nothing but a httphandler. This httphandler does not meant for a perticular extension or so. The job of this handler is to instantiate the controller and then process the request.
In MVC this handler is responsible for executing the ASP.NET lifecycle.

I am still exploring more on WebApi and lets see if we can get more indepth on this.