MVC Architecture And Its Pipeline

Introduction

MVC is not a programming language, it is simply a design pattern which is used to develop applications. MVC design pattern was very popular for development of Graphical User Interface (GUIs) applications, but now it is also popular in the designing of web applications, mobile and desktop etc. Many programming languages uses this pattern but we’ll discuss this in the context of ASP.NET.

Background

Last week one of my friends asked this question: "What is the MVC Architecture & its Pipeline?" and I am dedicating this article to him. I hope he will like this.

The topics to be covered are,

  • What does MVC mean
  • Understand MVC Architecture
    • Model in details
    • View in details
    • Controller in details
  • How does MVC architecture work?
  • What is Separation of Concerns
  • Characteristics of MVC
  • Pipeline in MVC

What does MVC mean?

In ASP.NET, model-view-controller (MVC) is the name of a methodology or design pattern for efficiently relating the user interface to underlying data models.

Understanding MVC

Model

It is responsible for maintaining the data and behavior of the application or it can be called the Business Layer. The classes in Models have properties and methods which represents the application state and rules and are called Entity classes or Domain classes, as well as these are independent of the User Interface (UI).

Models also contain the following type of logics,

  1. Business logic
  2. Data access logic
  3. Validation logic

Model classes are used to perform the validation logics and business rules on the data. These are not dependent on the UI so we can use these in different kind of applications. Simply, these are Plain Old CLR Objects (POCOs).

What is POCO?

The classes that we create in Model folder, are called POCOs. These classes contain only the state and behavior of the application and they don’t have the persistence logic of the application. That’s why these are called persistence ignorant objects. POCO class is,

  1. public class Student  
  2. {  
  3. }  

The main benefits of POCO's are really used when you start to use things like the repository pattern, ORM's and dependency injection. In other words – when we create an ORM (let's say EF) which pulls back data from somewhere (db, web service, etc.), then passes this data into objects (POCO's). Then if one day we decide to switch over to nHibernate from EF, we should not have to touch your POCO's at all, the only thing that should need to be changed is the ORM.

View

This layer represents the HTML markup that we display to the user. This can be called Display Layer. View is the user interface in which we render the Model in the form of interaction. The Views folder contains the .cshtml or .vbhtml files that clearly shows that these files are the combination of HTML and C#/VB code. In the Views folder, for every Controller there is a single view folder and for each action method in the controller there is a view in that view folder, having the same name as that of controller and action method respectively. There is also a Shared folder in the Views folder which represents the existence of Layout and Master Page in ASP.NET MVC.

Controller

When the user interacts with the user interface; i.e. View, then a HTTP request is generated which is in MVC architectural pattern, handled by Controller. So we can say that, Controller’s responsibility is to handle the HTTP request. This layer can also handle the input to the database or fetches the data from the database records. So it can be called Input layer.

The Controllers folder contains the classes that are responsible to handle HTTP requests. The name of the controller ends with the word Controller to differentiate it from other classes, for example, AccountController, HomeController. Every controller inherits from ControllerBase class which implements the IController interface which is coming from System.Web.Mvc namespace. IController interface's purpose is to execute some code when the request comes to controller. The look and feel of the IController is like this,

  1. using System.Web.Routing;  
  2. namespace System.Web.Mvc {  
  3.     {  
  4.         void Execute(RequestContext requestContext);  
  5.     }  
  6. }  

There is Execute method in IController class that gets executed when the request comes to controller. This method takes an object of RequestContext class, and this class encapsulates the information about the HTTP request that matches the defined route, with the help of HttpContext and RouteData properties. The look and feel of the RequestContext class is like this,

  1. using System.Runtime.CompilerServices;  
  2. namespace System.Web.Routing {  
  3.     // Encapsulates information about an HTTP request that matches a defined route.  
  4.     public class RequestContext {  
  5.         // Initializes a new instance of the System.Web.Routing.RequestContext class.  
  6.         public RequestContext();  
  7.         // Initializes a new instance of the System.Web.Routing.RequestContext class.  
  8.         // Parameters:  
  9.         // httpContext:  
  10.         // An object that contains information about the HTTP request.  
  11.         // routeData:  
  12.         // An object that contains information about route that matched the current  
  13.         // request.  
  14.         public RequestContext(HttpContextBase httpContext, RouteData routeData);  
  15.         // Summary:  
  16.         // Gets information about the HTTP request.  
  17.         // Returns:  
  18.         // An object that contains information about the HTTP request.  
  19.         public virtual HttpContextBase HttpContext {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         // Summary:  
  24.         // Gets information about the requested route.  
  25.         // Returns:  
  26.         // An object that contains information about the requested route.  
  27.         public virtual RouteData RouteData {  
  28.             get;  
  29.             set;  
  30.         }  
  31.     }  
  32. }  

The code is very self-explanatory with the help of comments.

Now the question is,  how does this architecture work?

The workflow of MVC architecture is given below, and we can see the request response flow of a MVC web application.
 
 

The figure is very self-explanatory and shows the work flow of MVC architecture. The client, which is the browser, sends a request to server (internet information server) and the Server finds a Route specified by the browser in its URL and through Route. The request goes to a specific Controller and then the controller communicates with the Model to fetch/store any records . Views are populated with model properties, and controller gives a response to the IIS7 server, as a result server shows the required page in the browser.

As we know, in MVC there are three layers which are interconnected to each other such as in the figure:

 

Here, in MVC there is complete separation in each layer, referred to as Separation of Concerns. Now, what exactly does Separation of Concerns mean?

What is Separation of Concerns?

Separation of concerns (SoC) is a design principle for separating a computer program into distinct sections, such that each section addresses a separate concern. A concern is a set of information that affects the code of a computer program. (Wikipedia)

MVC implements the principle of SoC as it separates the Model, View and Controller. Following is the table that depicts the implementation of SoC and Violation of SoC in ASP.NET MVC.

Implementation of SoC Violation of SoC
Views are only for displaying the HTML markup to the browser. When we use business logic in View then it is a violation because its sole purpose is to display the page not to execute the logic.
  1. @if (user.Role == "Admin") { }  
  2. else { }  
Controllers are just to handle the incoming HTTP request. When we use business logic in Controller like when controller executes the database logic to fetch/store the information in the database, it is a violation of single responsibility principle as well.
  1. publicActionResult Index() {  
  2.     If(ModelState.IsValid) {  
  3.         dbContext.Employees.Add(model);  
  4.     }  
  5.     Return RedirectToAction(“Saved”);  
  6. }  
Use Service layer to implement this business logic in the web application.
Models contain classes of the domain or business. When we use ViewBag and ViewData to pass the data from controller to view instead of using ViewModels to display data in view. ViewModels are classes that bind strongly typed views.
  1. publicActionResult Contact() {  
  2.     ViewBag.Message = "Your contact page.";  
  3.     return View();  
  4. }  
Use Repository pattern to access the data from the database.

Characteristics of MVC

These are the main characteristics of ASP.NET MVC,

  • Enables clean separation of concerns (SoC).
  • Follows the design of stateless nature of the web.
  • Provides Test Driven Development (TDD).
  • Easy integration with JavaScript frameworks.
  • Provides the full control over the rendered HTML.
  • No ViewState and PostBack events

Pipeline in MVC

We can say that pipeline of MVC contains the following processes,

  • Routing
  • Controller Initialization
  • Action Execution
  • Result Execution
  • View Initialization and Rendering

Let’s understand them one by one!

Routing

Routing is the first step in ASP.NET MVC pipeline. In fact, it is a pattern matching system that matches the incoming request to the registered URL patterns which reside in the Route Table.

Routing is a system in which URL patterns are matched with the URL patterns defined in the RouteTable by using MapRoute method. The process of Routing comes into action when the application starts, firstly it registered the routes in the RouteTable. This registration of routes in the RouteTable is essential because it is the only thing that tells the Routing Engine how to treat the requested URL requests. The routes are registered in the RouteConfig class App_Start file of the application. Let's have a look at it.

  1. public class RouteConfig {  
  2.     public static void RegisterRoutes(RouteCollection routes) {  
  3.         routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.         routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new {  
  5.             controller = "Home", action = "Index", id = UrlParameter.Optional  
  6.         });  
  7.     }  
  8. }  
The Global.asax file is look like,
  1. protected void Application_Start()  
  2. {  
  3.     //Some other code is removed for clarity.  
  4.     RouteConfig.RegisterRoutes(RouteTable.Routes);  
  5. }  
Routing Engine is the module whose responsibility is to treat the HTTP request. When HTTP request comes, the UrlRoutingModule starts matching the perfect URL pattern from the RouteTable, when find successfully, then Routing Engine forwards the request to RouteHandler.

In RouteHandler its interface IRouteHandler comes into action and calls its GetHttpHandler method. This method looks as below,
  1. public interface IRouteHandler  
  2. {  
  3.    IHttpHandler GetHttpHandler(RequestContext requestContext);  
  4. }  
After finding the route successfully, ProcessRequest() method is invoked, as shown in figure above, otherwise user will receive HTTP 404 error page.
 
 

Controller Initialization

While the ProcessRequest() method is invoked, it uses the IControllerFactory instance to create the controller for the URL request. The IContollerFactory is responsible to instantiate and return an appropriate controller and this created controller will become the subclass of the Controller base class.Then the Execute() method is invoked.
 
 

ProcessRequest() mehod looks like this,

  1. protected internal virtual void ProcessRequest(HttpContextBase httpContext) {  
  2.     SecurityUtil.ProcessInApplicationTrust(delegate {  
  3.         IController controller;  
  4.         IControllerFactory factory;  
  5.         this.ProcessRequestInit(httpContext, out controller, out factory);  
  6.         try {  
  7.             controller.Execute(this.RequestContext);  
  8.         } finally {  
  9.             factory.ReleaseController(controller);  
  10.         }  
  11.     });  
  12. }  

Action Execution

Action Execution starts with Action Invoker. So, after initialization of controller it has the information about the action method, this detail of action method is passed to controller’s InvokeAction() method. This InvokeAction() implements the interface IActionInvoler and hence the action is selected for invoking.
  1. public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)  
After ActionInvoker, Model Binders come into action. Model binders are used to retrieve the data from the HTTP request and after taking data from it, it applies the validation, and data type conversion rules on that data. For example, it check sits validity by comparing its data type with the data type of action parameters etc. Model Binders are present in System.Web.Mvc.DefaultModelBinder namespace.

When Model Binders take data from the requested URL then it is time to apply restrictions on the use of that data. So for this purpose, we have an Authentication filter that comes into action and authenticates the user whether that user is valid or not. You can apply authentication by using Authenticate attribute. And this authentication is done with the help of IAuthenticationFilter interface. So you can create your own by implementing it.

After authentication means after checking it the user is valid or not, the Authorization Filter comes into action and check the user access, which means who can use the data in which way. Authorization Filter applies to the authenticated user, it doesn’t apply to un-authenticated users. So authorization filter sets the user access for the authenticated user. You can use authorization filter by applying Authorize attribute at the top of action method. And this authorization is done with the help of IAuthorizationFilter interface. So you can implement it to create your own.

After collecting data from HTTP request, and performing authorization on any authenticated user, now is the time to execute the action. So our Action Filters come into play. Action Filters execute with the help of IActionFilter interface. And this interface has two methods that are executed before and after the action is executed, named OnActionExecuting and OnActionExecuted respectively. I’ll post another article on “How can we create custom action filter?”

After the execution of the Action, the ActionResult is generated. And hence the process of Action Execution is completed.

 

Result Execution

“Result Execution” module executes after the execution of module “Action Execution”, in this module Result Filters come into action and execute before and after the ActionResult executed. Result Filters are also implemented by IResultFilter, so you can create your own result filters by implementing this interface.

As you saw in the action execution section, you have Action Result as a result. There are many types of Action Results such as ViewResult, PartialViewResult, RedirectToRoute, RedirectResult, JsonResult, ContentResult and Empty Result. These types are all categorized into two main categories named as ViewResult and Non-ViewResult types.
  1. ViewResult type
    ViewResult is a type of result in which View of MVC part uses means in which a HTML page is rendered.

  2. NonViewResult type
    NonViewResult is a type of result which deals with only data. Data may be in text format, JSON format or binary format.
 

View Initialization and Rendering

View Engine takes ViewResult type and renders it as a View and shows it by using IView. IView interface looks like as below,

  1. public interface IView  
  2. {  
  3.    void Render(ViewContext viewContext, TextWriter writer);  
  4. }  
After rendering the View, it is the time to make Html Helpers that are used to write input fileds, create links, forms and much more. These helpers are extension mehod of HtmlHelper calss. Validation rules can also be applied, for example, view should use HtmlHelpers and render a form having client side validations.
 
 

Hence this is the pipeline of MVC. We have discussed each part very thoroughly.

Conclusion

This article included the basic and foremost things to understand about MVC architectural pattern and its pipeline. If you have any query then feel free to contact me in the comments. Also give feedback, either positive or negative, it will help me to make my articles better and increase my enthusiasm to share my knowledge.


Similar Articles