The Origin Of ASP.NET Core Web Application - A Ninja Guide

When you start working on the asp.net core application, you will notice that in the project solution there is a Program.cs file. This proogram.cs class has a main method that serves as the entry point for the application.
 

Create a console application in asp.net core

 
We will start this concept by creating a console application using Visual Studio 2019.
 
Here are the steps to create a console application,
  • Open visual studio 2019
  • Open the create a new project window (Go to file - New - Project or press ctrl+shift+N)

    create a new asp.net core project using visual studio

  • Choose the Console App (.Net Core) an click on the Next button.
  • Give a name to this project. Let's say the name is consoleToWeb

    configure the project

  • Click on the Create button.
  • This will create a new console application in the Visual Studio.
To view the files of this console aplication you can open the solution explorer. If the solution explorer is not visible then navigate to View (Menu at the top bar) and click on the Solution Explorer (Keyboard shortcut - Ctrl + Alt + L).
 

Steps to convert the console application to a web application

  • Make changes in the csproj file.
  • Add the host builder
  • Setup the startup class
  • Set a defaut route
Step 1 - Make changes in the csproj file
 
csproj is the project file and it is available in all types of projects of dot net core applications.
 
Here are the changes for the csproj file,
  • Update the project SDK
  • Remove the Output Type
  • Update the target framework monicker (TFM) to latest dot net core Monicker
To open the csproj file double click on the name of project in the visual studio. Alternatively you can right click on the project name and choose Edit Project File.
 
This is how the code of csproj file looks:
  1. <Project Sdk="Microsoft.NET.Sdk">    
  2.     
  3.   <PropertyGroup>    
  4.     <OutputType>Exe</OutputType>    
  5.     <TargetFramework>netcoreapp3.1</TargetFramework>    
  6.   </PropertyGroup>    
  7.     
  8. </Project>     
Update the project SDK
 
On the first line of this csproj file we need tp update the Sdk form Microsoft.NET.Sdk to Microsoft.NET.Sdk.Web.
 
Remove the Output Type
 
On the fourth line remove the <OutputType>Exe</OutputType>
 
Update the target framework monicker (TFM) to latest dot net core Monicker
 
The monicker for dot net core 5.0 is net5.0.
 
Now we need to use this net5.0 at the fifth line inside TargetFramework tag.
 
After making all the above changes, this is how the csproj file will look:
  1. <Project Sdk="Microsoft.NET.Sdk.Web">    
  2.     
  3.   <PropertyGroup>    
  4.     <TargetFramework>net5.0</TargetFramework>    
  5.   </PropertyGroup>    
  6.     
  7. </Project>     
Once you will save the changes then you need to focus on the explorer of this project. Here are some chages to notice - 
  • The application symbol has been updated from console to web.
  •  Inside the Dependencies folder we got new Analyzers and AspNetCore framework inside the Frameworks folder.
  • There is a new folder with name Properties and it has a launchSetting.json file.
Step 2 - Update the Program.cs file with the host builder
 
Asp.Net Core framework provides some features by default. We can add the suppost by using the host builder.
 
At this situation we need to configure two host builders in the application.
  1. Generic host builder
  2. Web host builder 
Generic host builder
 
We can add the generic host builder by using the CreateDefaultBuilder method.
 
This CreateDefaultBuilder method is availabe in the  Microsoft.Extensions.Hosting.Host class and it will add the  following features in the application.
  • Dependency Injection
  • Logging
  • IConfiguration
  • IHostedService Implementation
To set the generic host builder open the Program.cs class and create a new method with the name CreateHostBuilder and use the CreateDefaultBuilder method. 
  1. public static IHostBuilder CreateHostBuilder(string[] args)  
  2. {  
  3.     return Host.CreateDefaultBuilder(args);  
  4. }  
Web host builder
 
Now to give the support of HTTP and server we need to configure WebHostBuilder using ConfigureWebHostDefaults method.
 
This ConfigureWebHostDefaults method will add the following features in the application,
  • Add support of HTTP
  • Set the Kestrol server as the default web server.
  • Add support of IIS integration.
  1. public static IHostBuilder CreateHostBuilder(string[] args)  
  2. {
  3.     return Host.CreateDefaultBuilder(args)  
  4.     .ConfigureWebHostDefaults(webBuilder =>  
  5.     {  
  6.       });  
  7. }
Add the http request pipeline and inject the services we need to create a new class startup.cs and confine that class in the ConfigureWebHostDefaults.
 
Add a new class with name Startup.cs at the root level of your project.
  1. namespace consoleToWeb  
  2. {  
  3.     public class Startup  
  4.     {  
  5.     }  
  6. }  
Let's use this Startup class in this ConfigureWebHostDefaults method.
  1. public static IHostBuilder CreateHostBuilder(string[] args) =>  
  2. Host.CreateDefaultBuilder(args)  
  3. .ConfigureWebHostDefaults(webBuilder =>  
  4. {
  5.     webBuilder.UseStartup<Startup>();  
  6. });  
Note
You cannot rename CreateHostBuilder method as this exact name is required by the EF Core to configure the settings. Renaming this method might cause breaking changes with the EF Core.
 
Once we are done with the method implementation we need to call it in the Main method then build it and run it.
 
This is how the Program class will look like now,
  1. using Microsoft.AspNetCore.Hosting;  
  2. using Microsoft.Extensions.Hosting;  
  3. using System;  
  4.   
  5. namespace consoleToWeb  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             CreateHostBuilder(args).Build().Run();  
  12.         }  
  13.   
  14.         public static IHostBuilder CreateHostBuilder(string[] args)  
  15.         {  
  16.            return Host.CreateDefaultBuilder(args)  
  17.                 .ConfigureWebHostDefaults(webBuilder =>  
  18.                 {  
  19.                     webBuilder.UseStartup<Startup>();  
  20.                 });  
  21.         }  
  22.     }  
  23. }  
Note
You can also use the arrow method for CreateHostBuilder.
 
After using the arrow method here is final Program class.
  1. using Microsoft.AspNetCore.Hosting;  
  2. using Microsoft.Extensions.Hosting;  
  3. using System;  
  4.   
  5. namespace consoleToWeb  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             CreateHostBuilder(args).Build().Run();  
  12.         }  
  13.   
  14.         public static IHostBuilder CreateHostBuilder(string[] args) =>  
  15.             Host.CreateDefaultBuilder(args)  
  16.                 .ConfigureWebHostDefaults(webBuilder =>  
  17.                 {  
  18.                     webBuilder.UseStartup<Startup>();  
  19.                 });  
  20.     }  
  21. }  
Step 3 - Setup the startup class
 
Startup class plays a very important role in any asp.net core web application. This class is used to - 
  • Register the services in using the DI container
  • Setup the Http rquest pipeline to insert the middlewares.
Let's add the required method for the startup class.
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.DependencyInjection;  
  4.   
  5. namespace consoleToWeb  
  6. {  
  7.     public class Startup  
  8.     {  
  9.         public void ConfigureServices(IServiceCollection services)  
  10.         {  
  11.         }  
  12.   
  13.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  14.         {  
  15.         }  
  16.     }  
  17. }  

Step 4 - Add the routing in the application

 
To access any resource in the asp.net core web application we must configure the routing. Routing is basically a mapping between incoming http request and the resource.
 
We can enable the routing in Asp.Net Core  by using the following middleware.
  • UseRouting
  • UseEndpoints 
Let's insert both the middleware in the Http request pipeline i.e. Configure method.
  1. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  2. {  
  3.     app.UseRouting();  
  4.   
  5.     app.UseEndpoints(endpoints =>  
  6.     {  
  7.         endpoints.MapGet("/", async context =>  
  8.         {  
  9.             await context.Response.WriteAsync("Hello from new web application");  
  10.         });  
  11.     });  
  12. }  
Now if you will run the application, you will see  "Hello from new web application" output on your default browser.
 
You can also map more than one resouce using the MapGet() method.
 
After adding two more routes here is the Startup class, 
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.AspNetCore.Http;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5.   
  6. namespace consoleToWeb  
  7. {  
  8.     public class Startup  
  9.     {  
  10.         public void ConfigureServices(IServiceCollection services)  
  11.         {  
  12.         }  
  13.   
  14.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  15.         {  
  16.             app.UseRouting();  
  17.   
  18.             app.UseEndpoints(endpoints =>  
  19.             {  
  20.                 endpoints.MapGet("/", async context =>  
  21.                 {  
  22.                     await context.Response.WriteAsync("Hello from new web application");  
  23.                 });  
  24.   
  25.                 endpoints.MapGet("/test", async context =>  
  26.                 {  
  27.                     await context.Response.WriteAsync("Hello from new web application for test url");  
  28.                 });  
  29.   
  30.                 endpoints.MapGet("/about", async context =>  
  31.                 {  
  32.                     await context.Response.WriteAsync("Hello from new web application for about url");  
  33.                 });  
  34.             });  
  35.         }  
  36.     }  
  37. }  
Now you have a skeleton for the asp.net core web application.
 
You can use this template for MVC, WebAPI or Razor pages. You just need to inject the proper service in the ConfigureServices method and update the routing accordingly.
 
Changes for Asp.Net Core MVC application
 
We need to inject AddControllersWithViews in the ConfigureServices and MapDefaultControllerRoute() in the Configure method. 
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.DependencyInjection;  
  4.   
  5. namespace consoleToWeb  
  6. {  
  7.     public class Startup  
  8.     {  
  9.         public void ConfigureServices(IServiceCollection services)  
  10.         {  
  11.             services.AddControllersWithViews();  
  12.         }  
  13.   
  14.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  15.         {  
  16.             app.UseRouting();  
  17.   
  18.             app.UseEndpoints(endpoints =>  
  19.             {  
  20.                 endpoints.MapDefaultControllerRoute();  
  21.             });  
  22.         }  
  23.     }  
  24. }  
Changes for Asp.Net Core WebAPI application
 
We need to inject AddControllers in the ConfigureServices and MapControllers() in the Configure method.
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.DependencyInjection;  
  4.   
  5. namespace consoleToWeb  
  6. {  
  7.     public class Startup  
  8.     {  
  9.         public void ConfigureServices(IServiceCollection services)  
  10.         {  
  11.             services.AddControllers();  
  12.         }  
  13.   
  14.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  15.         {  
  16.             app.UseRouting();  
  17.   
  18.             app.UseEndpoints(endpoints =>  
  19.             {  
  20.                 endpoints.MapControllers();  
  21.             });  
  22.         }  
  23.     }  
  24. }  
Changes for Asp.Net Core Razor application

We need to inject AddRazorPages() in the ConfigureServices and MapRazorPages() in the Configure method.
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.DependencyInjection;  
  4.   
  5. namespace consoleToWeb  
  6. {  
  7.     public class Startup  
  8.     {  
  9.         public void ConfigureServices(IServiceCollection services)  
  10.         {  
  11.             services.AddRazorPages();  
  12.         }  
  13.   
  14.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  15.         {  
  16.             app.UseRouting();  
  17.   
  18.             app.UseEndpoints(endpoints =>  
  19.             {  
  20.                 endpoints.MapRazorPages();  
  21.             });  
  22.         }  
  23.     }  
  24. }  
 Dont forget to share your feedback in the comments section.