API Controllers decouples code from serialization of results: API:
public EventModel GetEvents(int quoteId, string market , string quote , int? pageNumber = null, int? pageSize = null)
{
var model = _eventsManager.GetEvents(quoteId, market, quote ,pageNumber, pageSize);
return model;
}
Content negotiation: Components called formatters serializes the data returned to the client. They are automatically selected based on the content of the Accept header of the incoming request. You can either use built- in formatter such as: JSON and Xml or replace them by modifying the configuration. Web API will resolve our objects to the suitable format using content negotiation. or actions that don’t match with one of those verbs, the default verb supported will be “POST”. Thus, we have to decorate all the actions that don’t meet with this naming conventions by one of the following attributes:
HttpGet
HttpPut
HttpPost
HttpDelete
MVC Controllers by default dispatch actions by name. A specific action name in a controller will directly map to the URL.
MVC
Action Result
Behavior
ContentResult
Sends raw data to the browser. It serialize any content it receives.
FileContentResult
Sends the content of the file to the browser.
FileStreamResult
Sends the content of the file to the browser (which is represented using Stream object).
HttpNotFoundResult
Sends HTTP 404 response code (Resource was not found).
Send HTML content to the browser and represents a page view.
PartialResult
Sends HTML content to the browser that represents a part of the whole page view.
WebAPI
Method
Behavior
BadRequest
Returns an HTTP 400 (“Bad Request”)
Conflict
Returns an HTTP 409 (“Conflict”)
Content
Returns Content (which is automatically negotiated or specified by the developer as media type formatter or content type)
Created
Returns an HTTP 201
InternalServerError
Returns an HTTP 500 (“Internal Server Error”)
Json
Returns an HTTP 200 (“OK”) and provides the content formatted in JSON
NotFound
Returns an HTTP 404 (“Not Found”)
Ok
Returns an HTTP 200 (“OK”)
Redirect
Returns an HTTP 302 (“Found”)
ResponseMessage
Returns the provided HttpResponseMessage
StatusCode
Returns a response with provided HTTP status code and an empty response body
Unauthorized
Returns an HTTP 401 (“Unauthorized)
HTTP Verbs Web API Controllers by default dispatch to actions by HTTP verbs. Action names will start with one of the verb names (GET, PUT, POST, and DELETE). For instance, Get, GetBooks, and GetById will map to the verb name “GET”.
Hosting
While MVC controllers can be consumed as services and do anything with additional coding, its main purpose is to build web HTML applications with some Ajax functions returning JSON data. On the other hand, Web API 2.0 is dedicated and specialized with transferring data and will be the optimal choice and the suitable development model that makes it easy to build RESTful services interface to different clients running on different platforms.