Introduction To ASP.NET Core Routing

Reading this article, you will get answers to the following questions.

  • What is Program.cs?
  • What is Startup.cs?
  • What is Routing?
  • What are necessary setting or steps for MVC and Routing?
  • What happens if you remove or comment services.AddMvc();?
  • How to add a Controller and a View?

What is Program.cs?

Basically, Program.cs is a kind of file that you will get in the console of the .NET application. The work of Program.cs file is to execute the code. Program.cs is a startup file to run the application.

In ASP.NET Core the Program.cs file is used to execute the BuildWebHost method. This method invokes UseStartup which calls the Startup.cs class file and get the application ready for hosting and routing things.

The BuildWebHost method then hosts the app and begins listening to the HTTP Requests.

Here is the sample code for a typical Program.cs file. 

  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;    
  7. using Microsoft.AspNetCore.Hosting;    
  8. using Microsoft.Extensions.Configuration;    
  9. using Microsoft.Extensions.Logging;    
  10. namespace CoreRouting {    
  11.     public class Program {    
  12.         public static void Main(string[] args) {    
  13.             BuildWebHost(args).Run();    
  14.         }    
  15.         //To build application web hosting.      
  16.         //Startup is Startup.cs file used here       
  17.         public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args).UseStartup < Startup > ().Build();    
  18.     }    
  19. }   

What is Startup.cs?

This is the main configuration file of every ASP.NET Core application. This file gets called inside Program.cs. The Startup.cs file contains the settings of middlewares, like MVC and routing.

In the below sample code, you can see there are two methods.

  • ConfigureServices that is used to declare and configure the services to be used in the application.
  • Configure method has two parameters.
    • IApplicationBuilder app - The IApplicationBuilder is used to build the middleware pipeline.
    • IHostingEnvironment env - The IHostingEnvironment is used to configure the hosting settings.

Here is the sample code of a typical Startup.cs file.

  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. namespace CoreRouting {  
  10.     public class Startup {  
  11.         // This method gets called by the runtime. Use this method to add services to the container.    
  12.         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940    
  13.         public void ConfigureServices(IServiceCollection services) {}  
  14.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.    
  15.         public void Configure(IApplicationBuilder app, IHostingEnvironment env) {  
  16.             if (env.IsDevelopment()) {  
  17.                 app.UseDeveloperExceptionPage();  
  18.             } else {}  
  19.             app.Run(async (context) => {  
  20.                 await context.Response.WriteAsync("Hello World!");  
  21.             });  
  22.         }  
  23.     }  
  24. }  

For more details, please visit this link.

Step by step implementation of Program.cs and Startup.cs

Create a new project called “CoreRouting” by selecting the application type as .NET Core >> ASP.NET Core Web application.
 
ASP.NET Core Routing 

Here are the details of the above screenshot.

  1. Select the .NET Core option from the left pane.
  2. Now, select ASP.NET Core Web Application option from the list in the middle pane.
  3. Give the project a name as “CoreRouting”. Check and confirm the path (Location), i.e., “D:\MBK\” in the above screen.
  4. Click the OK button.
On the next screen, select the options as described below.
  1. Select "Empty".
  2. Click "OK".

ASP.NET Core Routing 

This is the default screen after you clicked on OK.
 
ASP.NET Core Routing 

What is Routing?

Connecting an HTTP Request to the Controller is called routing. In an application, we can change the routing at the application level, controller level, and action level.

What are necessary settings or steps for MVC and Routing?

It is very simple to make an application ready for MVC and routing. Only three lines of code are required.

For Routing, we are going to use Startup.cs. Add the following lines of code to the ConfigureServices method in this file.

  • services.AddMvc();
  • Services.AddMvc() : To add the power of MVC.

Replace the default code of the Configure method with the following code.

  1. //To add MVC power  
  2. pp.UseMvc();    
  3.     
  4. //To add default routing mechanism  
  5. pp.UseMvcWithDefaultRoute();    

NOTEYou can see we have added only three lines of code in two methods only.

Tooltip of Visual Studio

Visual Studio shows the description of AddMvc in ToolTip.

ASP.NET Core Routing
 
ASP.NET Core Routing
 
ASP.NET Core Routing 

Updated code of Startup.cs file

  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.     
  10. namespace CoreRouting    
  11. {    
  12.     public class Startup    
  13.     {    
  14.         // This method gets called by the runtime. Use this method to add services to the container.    
  15.         // For more information on how to configure your application, visit                      //https://go.microsoft.com/fwlink/?LinkID=398940    
  16.         public void ConfigureServices(IServiceCollection services)    
  17.         {    
  18.             services.AddMvc();    
  19.         }    
  20.     
  21.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.    
  22.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)    
  23.         {    
  24.             //To add MVC power    
  25.             app.UseMvc();    
  26.     
  27.             //To add default routing mechanism     
  28.             app.UseMvcWithDefaultRoute();    
  29.         }    
  30.     }    
  31. }    

What happens if you remove or comment services.AddMvc();?

If you comment the services.AddMvc(); code inside of ConfigureServices method, you will get the following error screen which asks you to add the code of AddMvc service and your MVC will not work.

ASP.NET Core Routing 

Check MVC mechanism

To check the MVC mechanism, we will create a Controller and a View.

So far, our Solution Explorer looks like this.

ASP.NET Core Routing 

Now, we are going to add a Controller and a View.

Right-click on the project, select Add ---> New Item option to add a Controller.

ASP.NET Core Routing 
 
ASP.NET Core Routing 
  1. Select type as MVC Controller Class.
  2. Give this Controller Class a name.
  3. Click on the "Add" button.

The default code of HomeController.cs is like below.

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Threading.Tasks;    
  5. using Microsoft.AspNetCore.Mvc;    
  6.     
  7. // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860    
  8.     
  9. namespace CoreRouting    
  10. {    
  11.     public class HomeController : Controller    
  12.     {    
  13.         // GET: /<controller>/    
  14.         public IActionResult Index()    
  15.         {    
  16.             return View();    
  17.         }    
  18.     }    
  19. }    

Now, we are going to add a View for the Index action method.

  1. Right-click on Index ActionMethod.

    ASP.NET Core Routing

  2. Click on the "Add" button to add (generate) an Index.cshtml file.

    ASP.NET Core Routing

The system will create the following things.

  • VIEW folder - This folder will be created inside root.
  • Home Folder - This folder will be created inside the View folder.
  • Index.cshtml - This file will be crated at the following location 

     ~VIew/Home/Index.cshtml.

Let us have look at the code of Index.cshtml.

  1. @{    
  2.     Layout = null;    
  3. }    
  4. <!DOCTYPE html>    
  5.     
  6. <html>    
  7. <head>    
  8.     <meta name="viewport" content="width=device-width" />    
  9.     <title>Index</title>    
  10. </head>    
  11. <body>    
  12.     <h1>Welcome to CSharpCorner</h1>    
  13.     <br />    
  14.     <br />    
  15.     <h3>MVC running very well.</h3>    
  16. </body>    
  17. </html>    

Now, press F5 to check your ASEP.NET Core Web App.

OUTPUT

ASP.NET Core Routing 

Have you noticed the address bar? We have used default routing inside Startup.cs.

  1. //To add default routing mechanism   
  2. app.UseMvcWithDefaultRoute();  

Default route is home/index.

If you write this URL in the browser, the output will remain the same.

ASP.NET Core Routing