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)
- 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
- 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:
- <Project Sdk="Microsoft.NET.Sdk">
-
- <PropertyGroup>
- <OutputType>Exe</OutputType>
- <TargetFramework>netcoreapp3.1</TargetFramework>
- </PropertyGroup>
-
- </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:
- <Project Sdk="Microsoft.NET.Sdk.Web">
-
- <PropertyGroup>
- <TargetFramework>net5.0</TargetFramework>
- </PropertyGroup>
-
- </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.
- Generic host builder
- Web host builder
Generic host builder
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.
- public static IHostBuilder CreateHostBuilder(string[] args)
- {
- return Host.CreateDefaultBuilder(args);
- }
Web host builder
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.
- public static IHostBuilder CreateHostBuilder(string[] args)
- {
- return Host.CreateDefaultBuilder(args)
- .ConfigureWebHostDefaults(webBuilder =>
- {
- });
- }
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.
- namespace consoleToWeb
- {
- public class Startup
- {
- }
- }
Let's use this Startup class in this ConfigureWebHostDefaults method.
- public static IHostBuilder CreateHostBuilder(string[] args) =>
- Host.CreateDefaultBuilder(args)
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup<Startup>();
- });
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,
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Hosting;
- using System;
-
- namespace consoleToWeb
- {
- class Program
- {
- static void Main(string[] args)
- {
- CreateHostBuilder(args).Build().Run();
- }
-
- public static IHostBuilder CreateHostBuilder(string[] args)
- {
- return Host.CreateDefaultBuilder(args)
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup<Startup>();
- });
- }
- }
- }
Note
You can also use the arrow method for CreateHostBuilder.
After using the arrow method here is final Program class.
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Hosting;
- using System;
-
- namespace consoleToWeb
- {
- class Program
- {
- static void Main(string[] args)
- {
- CreateHostBuilder(args).Build().Run();
- }
-
- public static IHostBuilder CreateHostBuilder(string[] args) =>
- Host.CreateDefaultBuilder(args)
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup<Startup>();
- });
- }
- }
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.
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace consoleToWeb
- {
- public class Startup
- {
- public void ConfigureServices(IServiceCollection services)
- {
- }
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- }
- }
- }
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.
Let's insert both the middleware in the Http request pipeline i.e. Configure method.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- app.UseRouting();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapGet("/", async context =>
- {
- await context.Response.WriteAsync("Hello from new web application");
- });
- });
- }
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,
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.Http;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace consoleToWeb
- {
- public class Startup
- {
- public void ConfigureServices(IServiceCollection services)
- {
- }
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- app.UseRouting();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapGet("/", async context =>
- {
- await context.Response.WriteAsync("Hello from new web application");
- });
-
- endpoints.MapGet("/test", async context =>
- {
- await context.Response.WriteAsync("Hello from new web application for test url");
- });
-
- endpoints.MapGet("/about", async context =>
- {
- await context.Response.WriteAsync("Hello from new web application for about url");
- });
- });
- }
- }
- }
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.
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace consoleToWeb
- {
- public class Startup
- {
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllersWithViews();
- }
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- app.UseRouting();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapDefaultControllerRoute();
- });
- }
- }
- }
Changes for Asp.Net Core WebAPI application
We need to inject AddControllers in the ConfigureServices and MapControllers() in the Configure method.
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace consoleToWeb
- {
- public class Startup
- {
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllers();
- }
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- app.UseRouting();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
- }
Changes for Asp.Net Core Razor application
We need to inject AddRazorPages() in the ConfigureServices and MapRazorPages() in the Configure method.
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.DependencyInjection;
-
- namespace consoleToWeb
- {
- public class Startup
- {
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddRazorPages();
- }
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- app.UseRouting();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapRazorPages();
- });
- }
- }
- }
Dont forget to share your feedback in the comments section.