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 the 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.
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.
- 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
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 behaviour 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 logic,
- Business logic
- Data access logic
- Validation logic
What is POCO?
The classes that we create in Model folder, are called POCOs. These classes contain only the state and behaviour 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,
- public class Student
- {
- }
View
This layer represents the HTML markup that we display to the user. This can be called the Display Layer. The 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 an 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 the 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 the controller. The look and feel of the IController is like this,
- using System.Web.Routing;
- namespace System.Web.Mvc {
- {
- void Execute(RequestContext requestContext);
- }
- }
- 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;
- }
- }
- }
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 an MVC web application.
As we know, in MVC there are three layers which are interconnected to each other such as in the figure:
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.
|
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.
|
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.
|
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
We can say that the pipeline of MVC contains the following processes,
- Routing
- Controller Initialization
- Action Execution
- Result Execution
- View Initialization and Rendering
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.
- 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
- });
- }
- }
- protected void Application_Start()
- {
- //Some other code is removed for clarity.
- RouteConfig.RegisterRoutes(RouteTable.Routes);
- }
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);
- }
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.
- 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 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.
- public virtual bool InvokeAction(ControllerContext controllerContext, string actionName)
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” 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.
- ViewResult type
- NonViewResult type
View Engine takes ViewResult type and renders it as a View and shows it by using IView. IView interface looks like as below,
- public interface IView
- {
- void Render(ViewContext viewContext, TextWriter writer);
- }
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.
No comments:
Post a Comment