Introduction
In this article, we will discuss how we can convert a console application into an ASP.NET Core API. This article will make your base stronger, and you will gain exact information about the file hierarchy of a Console application project and a web API project. It will become interesting, because we’ll start with a console project and end it with a web API. I am using Visual Studio 2022. You can use what you have. Let’s start.
To convert a console Project into an ASP.NET Core API we need to follow these steps.
Step 1
Open visual studio and click on create a new project.
Figure-Creating New Project
Step 2
Select the console app and click next.
Figure-Choosing Project type
Step 3
Enter the Project name. In my case, I have entered ConsoleAppToWebAPI. You can choose the name based on your interest. Click on Next and select framework. I have chosen .NET Framework 6.0, which is the latest edition and has long-term support. Next, click the create button. Now our new console project has been created. So, let’s move to the next step.
Figure-Choosing Framework
If we run this application, the output would be a console output with a default hello word message.
Figure-Console Out-Put
Step 4
First, we need to make several changes to our project file. Double-click the project name, that is, ConsoleAppTowebAPI. First, we must change the output type of the project by adding .web next to Microsoft.NET.Sdk. It should look like the image below:
<Project Sdk="Microsoft.NET.Sdk.web">
Now our project will produce web-type output, and we will remove the output type Exe by removing the code written below:
<OutputType>Exe</OutputType>
By removing this code, our project will no longer produce .exe output. Here we used .NET 6.0. If you are using an older version or visual studio 2019 you can write:
<TargetFramework>net5.0</TargetFramework>
But, as I’m using Visual Studio 2022, I have written:
<TargetFramework>net6.0</TargetFramework>
After making these changes, our ProjectNmae.csproj should look like this:
<Project Sdk="Microsoft.NET.Sdk.web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
</PropertyGroup>
</Project>
Then click on save changes. When you click on save changes you will see a warning like the one picutred below:
Figure-Warning
This warning means that the changes we made on the project file require reloading the project to apply the changes. Now simply click Reload project. After clicking Reload Project, you will see that lots of changes have occurred once it has finished reloading. The icon of the project has changed, and now it looks like a web project. Some extra files were added to the project, like dependencies, etc.
Step 5
Now we add the host builder, and also configure the Program.cs file to create a web environment for the web API. Simply double-click on the Program .cs file. If you are working on .NET 5 you’ll get a default main program template with the hello world program, and if you are working on .NET6 you won't get the main method, but get a hello world line. Here we need a main method. Create a method named CreateHostBuilder and add this code:
using ConsoleAppToWebAPI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using System;
public class Program {
static void Main() {
CreateHostBuilder().Build().Run();
}
public static IHostBuilder CreateHostBuilder() {
return Host.CreateDefaultBuilder().ConfigureWebHostDefaults(webHost => {
webHost.UseStartup < Startup > ();
});
}
}
We need all these namespaces to use these features. First we created a static Method, CreateHostBuilder, with Return Type IHostBuilder, that returns default configurations for the Project using the Startup.cs.
public static IHostBuilder CreateHostBuilder() {
return Host.CreateDefaultBuilder().ConfigureWebHostDefaults(webHost => {
webHost.UseStartup < Startup > ();
});
}
We need to call this method in our main method.
static void Main() {
CreateHostBuilder().Build().Run();
}
Here we have used the Build() method to build the solution, and the Run() method to run the program. Now when the execution starts, the main method will be called CreateHostBuilder. This method adds hosting to our Project using the setting that is provided by the Startup.cs file. Now we need to add the Startup.cs file in our solution. We can simply add this file by placing the cursor on the error part <Startup> located in the CreateHostBuilder method, pressing CTRL+., and choosing suggestions to create a class with the name Startup.cs. Or, we can use the manual approach by right clicking on the project name and then clicking add, then choosing a class.
Figure-Adding Startup. cs class
Now, enter the name of the class as Startup. cs and click on Add button.
Figure-Adding Startup class
Step 7
Now we see that our error is solved. Now we need to enable Routing and use EndPoints in the Startup.cs file. So first, we must create a method with the name public void ConfigureServices(IServiceCollection services) in order to configure the services. This method uses IServiceCollection as a parameter, which is presented in the namespace Microsoft.Extensions.DependencyInjection. We also need a method with the name public void Configure(IApplicationBuilder app, IWebHostEnvironment env), which uses IapplicationBuilder and IwebHostEnvironmentas a parameter.
Here IapplicationBuilder is used to enable routing using UseRouting();. This is a method that is located in the namespace Microsoft.AspNetCore.Builder and in static class EndpointRoutingApplicationBuilderExtensions. IwebHostEnvironment is used to set an environment to run the web API, as it is an Interface. Now let's implement these methods.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
app.UseRouting();
app.UseEndpoints(endpoints => {
endpoints.MapGet("/", async context => {
await context.Response.WriteAsync("Hello from new web Api");
});
});
}
This method used a UseRouting() method that enabled the routing in our application. Another method is called the app.UseEndpoints, and it is used to configure endpoints. Endpoints are selected by the URLs and executed by the delegates. In this section:
endpoints.MapGet("/", async context => {
await context.Response.WriteAsync("Hello from new web Api");
});
We have used the endpoints.mapGet(), which is used to define endpoints. Under this mapGet method, we have defined the URL "/", which means this will be loaded when our application runs. Under this section, we have an async keyword that is used to execute code ssynchronously. Next, if we use the async keyword, then we have to use the await keyword. Await is used to return the operation that is performed by the async task. Next, we can write a hello message in context.Response.WriteAsync("Hello from new web API");. Now if we run our application, the code output will be:
Figur-Empty API out-put
At the beginning of the article when we executed the application, the output window was a console window with a hello world message. Now we can see that the output window is a web browser.
Step 8
Now we need to add API services to our controller. Let’s open our second method, which is ConfigureServices(IServiceCollection services). In API we don't need to add a view part, so here we add a controller using:
services.AddControllers();
in our ConfigureServices(IServiceCollection services) method by adding this line, we have the support of controllers. Now, we don't need this section:
MapGet("/", async context => {
await context.Response.WriteAsync("Hello from new web Api");
});
because now output will come from the Controller. Simply we use the app.MapControllers() method that helps in generating output from the controller.
Step 9
Now we need to add a folder in our project with the name Controllers. We can simply add a folder by right-clicking on project name, then add, then new folder. The name of the folder would be Controller.
Figure-Add controller Folder
Step 10
Now we need to add the Controller in the controller folder. So, right-click on the controller folder, then click on add, then choose controller, or we can choose a class. If we choose the controller, then some basic functionality will be added automatically. If we add the class, what will be added will be a simple class. Here, I've chosen class, then entered the class name NewController. Choose any name that you want, but use Controller as a suffix. This means that we must add "Controller" to the name of the controller.
Figure-Adding Controller
Now we have to inherit the class with ControllerBase, which is located at Microsoft.AspNetCore.MVC namespace. Next, we need to add [ApiController] that indicates that a type. All derived types will be used to serve HTTP API responses. Second, we must add the [Route()] attribute, where we can pass a custom route to our API.
using Microsoft.AspNetCore.Mvc;
namespace ConsoleAppToWebAPI.Controllers {
[ApiController]
[Route("NewApi/[action]")]
public class NewController: ControllerBase {
public string SayHii() {
return "Hii Learners";
}
}
}
[Route("NewApi/[action]")]
Now we can call our API with the Defined Route like here. To call an API, we need to pass /NewApi/sayHii. Here sayhii is an action you can create. Any other one or multiple actions can be invoked by their name. Now if I run this project, the output will be:
Figure-API Output
Now our API is ready with controllers, so we can add many more things to this API, like swigger UI and many more features.
Conclusion
In this article, we began with a console application with a console output, and now we have an API. We have made a lot of changes in our application. Still, we can make many more changes in our project.