ASP.NET MVC – Flashback of Important Concepts

A decade ago, ASP.NET Web Forms was the flagship framework for designing and developing web apps using .NET.

Over the years, developers had been demanding the ability to develop Web applications using a model-view-controller architecture. To address these needs and to stay current with the web development standards, Scott Guthrie of Microsoft designed the first ASP.NET MVC framework in October 2007.

Since then, a lot has changed in the world of ASP.NET MVC, but a lot is still the same. Although ASP.NET Core is the recommended option to develop web applications, as a developer, one should be aware of some important concepts that shaped the current framework.

This article provides an overview of the ASP.NET MVC technology for those who are still working on it, and explains some important components along the way.

The latest version of the MVC platform combines all the major frameworks (Web Forms, Web API, and MVC) under the umbrella of a single unified programming model.

Editor’s Note: Why did we need a unified platform?

ASP.NET offers three frameworks for creating web applications: ASP.NET Web Forms, ASP.NET MVC, and ASP.NET Web Pages. All three frameworks are mature, and you can create web applications with any of them however each has its own template, which gives a perception to the everyday developer that all these technologies are disjoint and distinct. This is far from true. The unified programming model changes this perception.

ASP.NET Core (previously known as ASP.NET 5) is the latest .NET stack to create modern web applications. It is a complete rewrite of ASP.NET and is open source, encourages modular programming, is cloud enabled, and is available across non-Microsoft platforms like Linux and Mac. In this stack, you have ASP.NET MVC, WEB API and Web Pages which have been unified and merged into one single unified framework earlier called as MVC 6, and now as ASP.NET Core. ASP.NET Web Forms is not a part of ASP.NET Core 1.0 although the WebForms team is actively maintaining the web forms framework, as well as adding new features to it whenever needed.

Although ASP.NET Core is a complete rewrite, all these technologies use .NET underneath and share a number of classes in the ASP.NET Core. So in Visual Studio 2015, you can develop an MVC application using ASP.NET Core Web Application Empty project template. Similarly you can create a Web Pages app using the same template. This unification will prove helpful for developers who are developing web applications using a single framework using various pieces of the ASP.NET platform as per the requirements.

For those interested in how ASP.NET has transformed to ASP.NET Core over the years, read this excellent 3 part series from Daniel called

The History of ASP.NET – Part I, II and III


ASP.NET MVC Release

Once ASP.NET MVC was released in 2007, it slowly became the preferred technology for web development. Since it provided out-of-box layers for Models, Controllers and View, Web Development with separation of concerns was made simpler albeit the learning curve.

We could use Visual Studio 2012/2013/2015 and now Visual Studio 2017 as well as 2019 for developing MVC application, where application scaffolding was easily provided to developers. Back then, we could create Model Objects using ADO.NET EntityFramework, ADO.NET Code, WCF Service Proxy, etc.

Once the Model layer was available to us, we could scaffold Controllers and Views. The only thing left for us was to write is the business code.

As modern developers, we often tend to ignore some of the major objects used in this architecture, which are also a part of the current frameworks.

In this article, we will go through these important objects. I hope this knowledge will help you understand the current framework in a much better way.

Major components of MVC

We have the following major components of MVC:

Model

  • This is the layer of MVC which defines Data Object Model (Entities/POCO) classes for the application, so that we can decide what data can be displayed on the View and what data property values can be accepted from the View. It is an Entity using which we scaffold Strongly Typed View. MVC scaffolding engine generates View based on the public properties of the Entity class to map them with HTML Helper Methods.
  • This layer can also contain business logic for the application, Calls to external services or existing class libraries.

Controllers

  • This is an important part of the MVC architecture. It is the controller layer which accepts an Http request from the end-user and processes it. This layer contain Action methods using which it interacts with the Model layer and performs data Read/Write operations. The return type from action methods is ActionResult. This object decides whether the response sent from the request is View, FileContent, JSON, etc.

Views

  • This is the User Interface layer of the application. This is the layer with which the end-user interacts. This layer is either scaffolded or designed based on the Model objects’ properties.

These layers can be conceptually represented using the following diagram:

The above diagram can be explained with following points based on the numbering on the arrows.

1. The controller interacts with the Model layer for performing Read/Write operations.

2. The Controller returns the View with Http Response.

3. The View is bound with the Model Object using Model binding. This Model binding, is used to validate the data entered by the end-user against validation rules applied on the Model properties or any other custom validation techniques.

After going through the MVC Components and its conceptual diagram, there are various other important concepts which every MVC developer must know so that we can implement MVC application effectively. These concepts are associated with following objects

1. RouteCollection.

2. ControllerContext.

3. ActionContext.

4. ViewContext.

5. ActionResult.

When we create a MVC project using Visual Studio 2012/2013/2015/2017 we are provided with Models, Controllers, Views, App_Start and App_Data folder. The App_Start folder contains RouteConfig.cs, class file. This file contains the RouteConfig static class with RegisterRoutes() method. This method accepts the RouteCollection object.

1. What is RouteCollection Object?

This object represents a collection of routes for ASP.NET MVC routing. The constructor of this class is used to build routes for the MVC application using the VirtualPathProvider. This is a provider for retrieving the resources from a virtual file system.

The RouteCollection is generated using the RouteTable class and its Routes property. The RouteTable, stores the URL routes for the MVC application. The RouteCollection object uses the MapRoute() method to map the specified URL route. This mapped URL is used for further request processing. When the MVC application starts, the Application_Start in Global.asax is executed which calls the RegisterRoutes() method from the RouteConfig class.

2. What is ControllerContext class?
The Controllers in MVC are responsible for responding to the end-users request.

The MVC Controller is derived from Controller base class, which is further derived from ControllerBase class and implements various interfaces.

The major interface implemented by the Controller base class is IController interface. During the MVC request processing when the Controller is instantiated, the request enters into the ControllerContext. This object is used to encapsulate the information about the current HTTP Request which matches with the specific Route and its Controller instance. This information is about the Action method being executed.

The ControllerContext object manages the actual execution of the various important objects used by the Controller class. The Controller base class, implements the following important interfaces

  • IActionFilter - Defines methods that are implemented for the logic that needs to be executed while executing Controller or Action method from it.
  • IAuthenticationFilter - Defines filter which is used for performing authentication. This is important when we need to controller the access of the Controller for a specific users.
  • IAuthorizationFilter - Defines methods those are required for an authorization process in the Controller and its Action methods. This is used in Role based security in MVC.
  • IExceptionFilter - This is used for managing runtime exception handling in MVC request processing.
  • IResultFilter - This defines methods those are required for result filters.

These action filters plays an important role in MVC request processing. These Action Filters defines what other objects are used while executing the MVC Controller. The MVC Controller while executing uses ActionInvoker property of the type IActionInvoker. This invokes an action from the Controller class specified in the routing expression.

3. What is an ActionContext?

ActionContext represents the current action under execution.

This goes into two steps, the ActionExecutingContext and ActionExecutedContext classes. The former represents the action execution process where the logic in the action method gets executed, where as the later represents the action completing its execution and either the Result or an exception is thrown.

The object returned from the Action method is ActionResult class. This is an abstract class which has the following derived classes.

  • ViewResult - Represent the HTML Markup. The Html rendered view.
  • EmptyResult -  No result.
  • RedirectResult - Redirect to the new URL.
  • JsonResult - Returns JSON result which can be used in an AJAX applications.
  • JavaScriptResult - Represents a JavaScript.
  • ContentResult - Represent the Text result.
  • FileContentResult - Represents a downloaded file with binary contents.
  • FilePathResult - Represents a downloaded file with a path.
  • FileStreamResult - Represents a downloaded file with stream.

4. What is ViewContext Class?

This class encapsulate the information regarding View rendering. This class is uses when an Action method returns ViewResult.

The ViewResult class is derived from the ActionResult abstract class. The ViewResult is responsible for loading the View Engine (E.g. Razor View Engine or Custom View Engine). Once the View is loaded, it executes all the Html Helper methods along with the Model Binding so that data can be shown to the end-user or the data entered by the end-user can be validated.

Let us see the use of all the important objects in MVC Request processing in the following diagram:


The above request processing has the following sections:

  • MVC Routing
    • This intercepts the incoming request and matches it with the URL in the RouteTable.
    • This provides the Controller and its corresponding action method from the request URL.
  • The HttpHandler is responsible for processing the request further with ControllerContext.
  • The ControllerContext, instantiates the Controller class with the help of ControllerFactory.
    • This loads and executes ActionFilter if applied. These Action Filters can be Authentication, Authorization, Exception or any other custom filters.
    • The Action is invoked using Action Invoker.
  • The action execution is handled using ActionExecutingContext.
    • This loads and executes ActionFilter if applied. These Action Filters can be Authentication, Authorization, Exception or any other custom filters.
    • The action execution is completed, this completes the ActionExecutedContext.
  • Once the action is executed, this returns an ActionResult. If the action result is ViewResult, the control is entered into the ViewContext
    • Loads and executed ViewEngine.
    • Loads Html helper methods on the view.
    • The HtmlHelper are executed with the Mode Binding expressions.
    • The Html response is rendered
  • If the ActionResult is not ViewResult then various derived instances of ActionResult are executed, e.g. JsonResult, FilePathResult, etc.

Conclusion: The MVC request processing is one of the major important section of MVC to understand. This information further helps developers to extend MVC using various mechanism where Custom Filters, Authorization and Authentication, etc. can be implemented.

I hope this knowledge will he useful when you will be working on advanced frameworks like ASP.NET Core. Read more about ASP.NET Core at www.dotnetcurry.com/tutorials/aspnet-core




About The Author

Mahesh Sabnis is a Microsoft MVP having over 18 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

No comments: