Introduction
This article explains the differences between ASP.NET MVC and ASP.NET Web API and also describes how to combine the Web API with the MVC.
ASP.NET MVC
ASP.NET MVC is a web application framework. It divides an application into the three parts, Model, View and Controller. It is an alternative of traditional ASP.NET Web Forms in creating Web applications. MVC framework Combines the ASP.NET features such as Master pages, Membership based authentication. MVC libraries exist in the “System.Web.MVC” assembly.
ASP.NET MVC is composed of three components:
- Model: Model represents the object used to retrieve, process and store the data in the database.
- View: View directly presents the User Interface (UI) to user. It renders and displays the data model.
- Controller: Controller manages the interaction between Model and View. It accepts the user requests & inputs, invokes model to grab data, then chooses a view for displaying the UI.
The Models retrieve the information and store the updated information in the database. Views are used for only displaying the information, and the controllers are used for managing and responding to the user inputs and their interaction.
Sample MVC controller:
public class BooksController: Controller
{
public ActionResult Details(int id)
{
var book = _repository.GetBook(id);
if (book == null) returnnewHttpNotFoundResult();
return View(book);
}
}
ASP.NET Web API
ASP.NET Web API is a framework that provides HTTP services. It displays the data in various formats, such as XML and JSON and makes it easy to provide the response to the client request. The request may be GET, POST, DELETE or PUT. The response depends on the request of the clients. MVC libraries exist in the “System.Web.Http” assembly.
Major features:
- Provides HTTP services.
- Designed for reaching the broad range of clients
- Consumed by other HTTP applications, not users
Sample Web Api controller:
public class BooksController: ApiController
{
public Book GetById(int id)
{
var book = _repository.GetBook(id);
if (book == null) throw new HttpResponseException(HttpStatusCode.NotFound);
return book;
}
}
Please note that Web API supports content negotiation and can resolve our objects to the suitable format. In this example the book object can be converted to JSON or XML or replace them by modifying the configuration. The response is automatically selected based on the content of the Accept header of the incoming request.
Every method in Web API will return data (JSON) without serialization. However, in order to return JSON Data in MVC controllers, we have to set the returned Action Result type to JsonResult and call the Json method on our object to ensure it is packaged in JSON.
public JsonResult GetBooks()
{
var books = _repository.GetBooks();
return Json(books, JsonRequestBehavior.AllowGet);
}
or customize the result by installing Newtonsoft.JSON.NET library first:
public JsonResult GetBooks()
{
var books = _repository.GetBooks();
var result = JsonConvert.SerializeObject(books, Formatting.None, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore, ContractResolver = new CamelCasePropertyNamesContractResolver()});
return Json(result, JsonRequestBehavior.AllowGet);
}
Typically, Web Api can be used to create RESTful web services:
e.g.
GET /products
- get a list of all products
GET /products/81
- get product details with ID of 81
GET /products/81/items
- get a list of all items of the product with ID of 81
GET /products?Colour=red
- get a list of all products in the system where the colour is red
POST /products
- create a new product
PUT /products/81
- update the product with an ID of 81
DELETE /products/81
- delete the product with an ID of 81
Difference between MVC and Web API
Although MVC and Web API consists of similar components such as Controllers, Actions, Filters, Routes, they are implemented by different types of classes in different assemblies.
The purpose of them is different. MVC is used to create websites and web API is used to create services/APIs. Or MVC is meant to output HTML where Web API is meant to output raw data:
- MVC is used to develop the Web application that replies as both data and views but the Web API is used for generating the HTTP services that replies only data not view.
- Web API returns the data in various formats, such as JSON, XML and other format based on the accept header of the request. But the MVC returns the data in the JSON format by using JSONResult.
- Web API supports content negotiation. MVC does not support.
- Web API supports IIS hosting and self hosting (hosted via process). MVC only supports IIS hosting.
- Web API includes the various features of the MVC, such as routing, model binding but these features are different and are defined in the “System.Web.Http” assembly. And the MVC features are defined in the “ System.Web.Mvc” assembly.
- Web API supports the creation of RESTful services over the .Net Framework but the MVC does not support.
- Web API is light weight architecture and besides the web application it can also be used with smart phone apps. MVC is only designed for web applications.
Combine MVC with Web API
MVC can be used to create a full-featured web application. If we hope to expose portions of functionality as RESTful web services that can be called upon using HTTP requests (such as AJAX calls from the multiple client). We can add Web Api Controllers to do that. In this case, MVC controllers and Web Api controllers share the same business services layer.
As a result, we can have
GET /users/1
- MVC
GET /api/users/1
- Web API
References
Use ASP.NET Web Api to create REST services:
https://www.codeproject.com/Articles/1092504/Creating-Self-Hosted-ASP-NET-WebAPI-with-CRUD-oper
http://www.cnblogs.com/TianFang/p/3728760.html
http://www.cnblogs.com/MQNH/p/5629069.html
-
Previous
SQL Tips - over, partition by, row_number and rank -
Next
ASP.NET WebApi file upload implementation