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 use 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 the 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 that represent 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 types of logic.

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

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

What is POCO?

The classes that we create in the 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 persistent ignorant objects. POCO class is,

public class Student
{
}

The main benefits of POCOs are really used when you start to use things like the repository pattern, forms, and dependency injection. In other words – when we create an ORM (let's say EF) that pulls back data from somewhere (DB, web service, etc.), then passes this data into objects (POCOs). Then if one day we decide to switch over to NHibernate from EF, we should not have to touch your POCOs 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 the 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 which 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 the 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 an HTTP request is generated which is in the MVC architectural pattern, handled by the Controller. So we can say that the Controller’s responsibility is to handle the HTTP request. This layer can also handle the input to the database or fetch the data from the database records. So it can be called the Input layer.

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

using System.Web.Routing;

namespace System.Web.Mvc
{
    {
        void Execute(RequestContext requestContext);
    }
}

There is an Execute method in the IController class that gets executed when the request comes to the controller. This method takes an object of the 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.

using System.Runtime.CompilerServices;

namespace System.Web.Routing
{
    // Encapsulates information about an HTTP request that matches a defined route.
    public class RequestContext
    {
        // Initializes a new instance of the System.Web.Routing.RequestContext class.
        public RequestContext();

        // Initializes a new instance of the System.Web.Routing.RequestContext class.
        // Parameters:
        // httpContext:
        // An object that contains information about the HTTP request.
        // routeData:
        // An object that contains information about route that matched the current
        // request.
        public RequestContext(HttpContextBase httpContext, RouteData routeData);

        // Summary:
        // Gets information about the HTTP request.
        // Returns:
        // An object that contains information about the HTTP request.
        public virtual HttpContextBase HttpContext
        {
            get;
            set;
        }

        // Summary:
        // Gets information about the requested route.
        // Returns:
        // An object that contains information about the requested route.
        public virtual RouteData RouteData
        {
            get;
            set;
        }
    }
}

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

How does this architecture work?

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

MVC Web

The figure is very self-explanatory and shows the workflow of MVC architecture. The client, which is the browser, sends a request to the 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 the 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 that are interconnected to each other such as in the figure.

Model

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 the 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.

@if (user.Role == "Admin") { }
else { }
Controllers are just to handle the incoming HTTP request.

When we use business logic in the Controller like when the controller executes the database logic to fetch/store the information in the database, it is a violation of single responsibility principle as well.

public ActionResult Index()
{
    if (ModelState.IsValid)
    {
        dbContext.Employees.Add(model);
    }
    return RedirectToAction("Saved");
}

Use the 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. Use the Repository pattern to access the data from the database.

public ActionResult Contact()
{
    ViewBag.Message = "Your contact page.";
    return View();
}


Characteristics of MVC

These are the main characteristics of ASP.NET MVC,

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

Pipeline in MVC

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

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

Let’s understand them one by one!

Routing

Routing is the first step in the 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 the MapRoute method. The process of Routing comes into action when the application starts, firstly it registers 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.

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new
            {
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            }
        );
    }
}

The Global. asax file looks like.

protected void Application_Start()
{
    // Some other code is removed for clarity.
    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

The Routing Engine is the module whose responsibility is to treat the HTTP request. When an HTTP request comes, the UrlRoutingModule starts matching the perfect URL pattern from the RouteTable, when found successfully, the 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.

public interface IRouteHandler
{
    IHttpHandler GetHttpHandler(RequestContext requestContext);
}

After finding the route successfully, the ProcessRequest() method is invoked, as shown in the figure above, otherwise, user will receive an HTTP 404 error page.

ProcessRequest

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.

Controller Initialization

ProcessRequest() method looks like this.

protected internal virtual void ProcessRequest(HttpContextBase httpContext)
{
    SecurityUtil.ProcessInApplicationTrust(delegate
    {
        IController controller;
        IControllerFactory factory;
        this.ProcessRequestInit(httpContext, out controller, out factory);
        try
        {
            controller.Execute(this.RequestContext);
        }
        finally
        {
            factory.ReleaseController(controller);
        }
    });
}

Action Execution

Action Execution starts with Action Invoker. So, after the initialization of controller, it has the information about the action method, this detail of the action method is passed to the controller’s InvokeAction() method. This InvokeAction() implements the interface IActionInvoler and hence the action is selected for invoking.

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 checks its validity by comparing its data type with the data type of action parameters, etc. Model Binders are present in the 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 the Authenticate attribute. This authentication is done with the help of the IAuthenticationFilter interface. So you can create your own by implementing it.

After authentication after checking it the user is valid or not, the Authorization Filter comes into action and checks 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 unauthenticated users. So authorization filter sets the user access for the authenticated user. You can use the authorization filter by applying the Authorize attribute at the top of the action method. And this authorization is done with the help of the IAuthorizationFilter interface. So you can implement it to create your own.

After collecting data from HTTP requests, 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 the IActionFilter interface. 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 a custom action filter?”

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

 ActionResult

Result Execution

The “Result Execution” module executes after the execution of the module “Action Execution”, in this module Result Filters come into action and execute before and after the ActionResult is 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 the View of MVC part uses means by which an HTML page is rendered.
  2. NonViewResult type: NonViewResult is a type of result that deals with only data. Data may be in text format, JSON format, or binary format.
    Asp.Net

View Initialization and Rendering

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

public interface IView
{
    void Render(ViewContext viewContext, TextWriter writer);
}

After rendering the View, it is time to make HTML Helpers that are used to write input files, create links, forms, and much more. These helpers are extension methods of the HTML helper class. Validation rules can also be applied, for example, view should use HtmlHelpers and render a form having client-side validations.

Result filter

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