Route Concept With MVC Pattern In .NET Core Application - Day Seven

In the previous article of this series, we discussed about the basic route concept within .NET Core Application. Now in this article, we will discuss how can we use route with MVC (Model –View – Controller pattern in .NET Core). 

In the previous article, we use the route parameters within the StartUp.cs file but this approach is not the actual route concept followed by the MVC pattern. In this article, we will discuss how to implement the same route concept with MVC pattern. Thus, before demonstrating the code, we will discuss about MVC pattern.

What is the MVC pattern?

ASP.NET Core MVC is a rich framework to build Web apps and APIs, using Model-View-Controller design pattern. Model-View-Controller (MVC) architectural pattern separates an Application into three main groups of components, which are Models, Views and Controllers. This pattern helps to achieve separation of concerns. Using this pattern, the user requests are routed to a Controller, which is responsible for working with Model to perform user actions and/ or retrieve the results of the queries. The Controller chooses the View to display to the user and provides it with any Model data, it requires.

The diagram given below shows three main components and they reference each other.

 

This delineation of responsibilities helps you scale the application in terms of complexity because it’s easier to code, debug, and test something (model, view, or controller) that has a single job. It's more difficult to update, test, and debug code that has dependencies spread across two or more of these three areas. For example, user interface logic tends to change more frequently than business logic. If presentation code and business logic are combined in a single object, you have to modify an object containing business logic every time you change the user interface. This is likely to introduce the errors and require the retesting of all business logic after every minimal user interface change.

Model responsibilities

Model in an MVC Application represents the state of the Application and any business logic or operations, which should be performed by it. Business logic should be encapsulated in the Model, along with any implementation logic for persisting the state of the Application. Strongly-typed views will typically use ViewModel types specifically.

View responsibilities

Views are responsible to present the content through the user interface. They use Razor View engine to embed .NET code in HTML markup. There should be minimal logic within Views and any logic in them should relate to present the content. If you find the need to perform a great deal of logic in View files in order to display the data from a complex model, consider using a View Component, ViewModel or view template to simplify the view.

Controller responsibilities

Controllers are the components that handle user interaction, work with the Model and ultimately select a view to render. In an MVC Application, View only displays information; Controller handles and responds to user input and interaction. In the MVC pattern, Controller is the initial entry point and is responsible to select which model types to work with and which View to render (hence its name - it controls how the app responds to a given request).

What is ASP.NET Core MVC

ASP.NET Core MVC framework is a lightweight, open source, highly testable presentation framework optimized for use with ASP.NET Core. ASP.NET Core MVC provides a pattern-based way to build dynamic websites, which enables a clean separation of concerns. It gives you full control over markup, supports TDD-friendly development and uses the latest Web standards.

Features

ASP.NET Core MVC includes the features given below.

Routing 

  • Model binding
  • Model validation
  • Dependency injection
  • Filters
  • Areas
  • Web APIs
  • Testability
  • Razor View engine
  • Strongly typed Views
  • Tag Helpers
  • View Components 

Now, as per the features given above, we will discuss about routing feature in this article. We will discuss about the other features in the other articles of this series later on.

ASP.NET Core MVC is developed on top of ASP.NET Core's routing architecture, a powerful URL-mapping component, which lets you build Applications that have comprehensible and searchable URLs. This enables you to define your Application's URL naming patterns, which works well for search engine optimization (SEO) and for link generation without considering for how the files are located on your Web Server are organized. You can define your routes, using a convenient route template syntax, which supports route value constraints, default and optional values. ASP.NET Core MVC supports two types of routing conventions –

Convention-based routing 

This type of routing enables you to globally define the URL formats, which your Application accepts and how each of those formats maps to a specific action method on a given Controller. When an incoming request is received, the routing engine parses the URL and matches it to one of the defined URL formats and subsequently calls the associated Controller's action method.

  1. routes.MapRoute(name: "Default", template: "{controller=Home}/{action=Index}/{id?}");  

Attribute routing 

This type of routing enables you to specify routing information by decorating your Controllers and actions with the attributes, which define your Application's routes. This means that your route definitions are placed next to the Controller and action with which they are associated.

  1. [Route("api/[controller]")]  
  2. public class ProductsController : Controller  
  3. {  
  4.    [HttpGet("{id}")]  
  5.    public IActionResult GetProduct(int id)  
  6.    {  
  7.       //code  
  8.    }  
  9. }  

Now, use MVC pattern and we need to install two NuGet Package named, 

  1. Microsoft.AspNetCore.Routing
  2. Microsoft.AspNetCore.Mvc 


Now, write down the code given below, as per the file name.
 
Startup.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Builder;  
  6. using Microsoft.AspNetCore.Hosting;  
  7. using Microsoft.AspNetCore.Http;  
  8. using Microsoft.Extensions.DependencyInjection;  
  9. using Microsoft.Extensions.Logging;  
  10.   
  11. namespace Prog6_MvcPatternRoute  
  12. {  
  13.     public class Startup  
  14.     {  
  15.         // This method gets called by the runtime. Use this method to add services to the container.  
  16.         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940  
  17.         public void ConfigureServices(IServiceCollection services)  
  18.         {  
  19.             services.AddMvc();  
  20.         }  
  21.   
  22.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  23.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  24.         {  
  25.             loggerFactory.AddConsole();  
  26.   
  27.             if (env.IsDevelopment())  
  28.             {  
  29.                 app.UseDeveloperExceptionPage();  
  30.             }  
  31.   
  32.             app.UseMvc();  
  33.         }  
  34.     }  
  35. }  
Program.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.IO;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6. using Microsoft.AspNetCore.Hosting;  
  7.   
  8. namespace Prog6_MvcPatternRoute  
  9. {  
  10.     public class Program  
  11.     {  
  12.         public static void Main(string[] args)  
  13.         {  
  14.             var host = new WebHostBuilder()  
  15.                 .UseKestrel()  
  16.                 .UseContentRoot(Directory.GetCurrentDirectory())  
  17.                 .UseIISIntegration()  
  18.                 .UseStartup<Startup>()  
  19.                 .UseApplicationInsights()  
  20.                 .Build();  
  21.   
  22.             host.Run();  
  23.         }  
  24.     }  
  25. }  
Now, add a folder name Controller and create a class file within the folder name HelloWorldController.cs and write down the code given below.
  1. using Microsoft.AspNetCore.Mvc;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Threading.Tasks;  
  6.   
  7. namespace Prog6_MvcPatternRoute.Controller  
  8. {  
  9.     public class HelloWorldController  
  10.     {  
  11.         [HttpGet("/")]  
  12.         public string Index() => "This is MVC Pattern Concept";  
  13.   
  14.         [HttpGet("/Hello")]  
  15.         public string Hello() => "Hello!! This is MVC Pattern Concept";  
  16.     }  
  17. }  
Now, as per the code given above, we will create two route keys, where one is default route key and another is /Hello key. Now, run the code and the output is given below.
 

You can read the next part here,