ASP.NET Core Web API Files and Folders

ASP.NET Core Web API Files and Folders

In this article, I am going to discuss the Default ASP.NET Core Web API Files and Folders i.e. the Files and Folders which are created by default when we create a new ASP.NET Core Web API Application. Please read our previous article where we discussed How to Create, Build, and Run ASP.NET Core Web API in Visual Studio 2022 using ASP.NET Core 6.

Folders and Files in ASP.NET Core Web API:

ASP.NET Core 6.0 is a cross-platform framework for building web APIs, among other types of applications. It provides a lightweight, modular, and high-performance platform for developing web services. The file structure of an ASP.NET Core 6.0 Web API project typically follows a standard convention.

In our previous article, we created the first ASP.NET Core Web API Project using Visual Studio 2022 and we also see that the project is created with the following files and folder structure.

ASP.NET Core Web API Files and Folders

Let’s go over the common file structure of an ASP.NET Core 6.0 Web API project. Now let us proceed and understand the above files and folders in detail.

Dependencies:

The Dependencies contain all the packages and SDKs that are installed in this project. Further, if you expand, it contains three files (Analyzers, Frameworks, and Packages) as shown in the below image.

Dependencies in ASP.NET Core Web API Application

Packages:

At the moment the Packages folder contains one package i.e. Swashbuckle.AspNetCore. If you remember when we run the application, then it opens the swagger page. This package is basically for Swagger. Later if you add any new packages to your project, then those packages will be shown here.

Frameworks:

The framework contains two folders i.e. Microsoft.AspNetCore.App and Microsoft.NETCore.App. All the packages that are required to run ASP.NET Core Application will be there inside Microsoft.AspNetCore.App file. The ASP.NET Core is a framework that is written on top of the .NET Core. So, all those packages that are required for the .NET core are available inside Microsoft.NETCore.App. So, the point that you need to remember is .NET Core and ASP.NET Core are two different things. All the packages which are specific to ASP.NET Core will reside inside Microsoft.AspNetCore.App and all the packages which are specific to .NET Core will reside inside Microsoft.NETCore.App.

Analyzers:

The ASP.NET Core 2.2 and later provides analyzer packages intended for use with Web API projects. The analyzers will work with controllers annotated with ApiControllerAttribute while building on Web API conventions. The analyzers package notifies you of any controller action that:

  1. Returns an undeclared status code.
  2. Returns an undeclared success result.
  3. Documents a status code that isn’t returned.
  4. Includes an explicit model validation check.
Properties:

The Properties Folder in ASP.NET Core Web Application by default contains one JSON file called launchsettings.json file as shown in the below image.

Properties in ASP.NET Core Web API

The launchsettings.json file contains some settings that are going to be used by .NET Core Framework when we run the application either from Visual Studio or by using .NET Core CLI. Another point that you need to keep in mind, the launchSettings.json file is only used within the local development machine. So, this file is not required when we publish our ASP.NET Core Web API application into the production server. Now, open the launchSettings.json file, by default, you will see the following settings.

launchsettings.json file in ASP.NET Core Web API

If you remember, when we are running our application using .NET Core CLI, we are getting two URLs (https://localhost:5001 and http://localhost:5000). These two URLs are coming from this MyFirstWebAPIProject Profile.

Further, if you remember when we run our application using Visual Studio, the application ran on port number 44395. For IIS Express Profile, it uses iissettings. If you notice the iisSettings, the applicationUrl is http://localhost:63044, and sslPort is 44395. That means if you are running the application using the HTTP protocol, then it will use the 63044 port number and if you run the application using the HTTPS protocol then it will use the 44395 port number.

Note: If you are running your application from Visual Studio then IIS Express Profile will be used (for HTTP the port number will be 63044 and for HTTPS the port number will be 44395). On the other hand, if you are running your application using .NET Core CLI, then the MyFirstWebAPIProject profile will be used which is nothing but using Kestrel Web Server, and for HTTP protocol it uses the port number 5000 and for HTTPS protocol it uses the port number 5001.

Learn More about the launchsettings.json file.

Controllers:

The ASP.NET Core Web API is a Controller-Based Approach. All the controllers of your ASP.NET Core Web API Application should and must reside inside the Controllers folder. This directory contains the API controllers that handle incoming HTTP requests. Controllers define action methods that respond to specific routes and perform the desired logic. Here, by default, one controller is there inside the Controllers folder as shown in the below image.

Controllers in ASP.NET Core Web API

If you open the WeatherForecastController file, then you will find the following code in it. The Controller class is inherited from the ControllerBase class and decorated with ApiController and Route attributes. We will discuss all these things in detail in our upcoming article.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyFirstWebAPIProject.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

As you can in the above code, we have one Get method which is decorated with the HttpGet attribute. And when we call the following URL using any client (Swagger, Postman, and Browser), this is the method going to return the data. We will discuss Controller in detail in our upcoming articles.

https://localhost:44395/WeatherForecast

appsettings.json file:

The next file that we are going to discuss is the appsettings.json file. This is the same as the web.config or app.config of our traditional .NET Application. The appsettings.json file is the application configuration file in ASP.NET Core Web Application used to store the configuration settings for your application, such as database connection strings, API keys, and logging settings.

This JSON file stores configuration settings for your application. You can define various settings like database connection strings, logging configuration, and other custom settings. If you open the appsettings.json file, then you see the following code by default which is created by .NET Core Framework when we created the ASP.NET Core Web API Application.

appsettings.json file in ASP.NET Core Web API

Learn More about the appsettings.json file.

appsettings.Development.json:

This file is an extension of the JSON file and is used specifically for development environment configuration. It can override or add settings that are specific to the development environment. That means if you want to configure some settings based on the environments then you can do such settings in appsettings.{Environment}.json file. You can create n number of environments like development, staging, production, etc. 

If you set some settings in the appsettings.Development.json file, then such settings can only be used in the development environment, and can not be used in other environments. If you open the appsettings.Development.json file, then you will get the following code in it. In our upcoming articles, we will see how to create and use different environment appSettings files in ASP.NET Core Web API Application.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}
Program.cs class file:

The Program.cs class file of our ASP.NET Core Webb API Application contains the following code. With .NET 6, there is no startup class. All the startup class codes are now moved to the Main method of the Program class. This file contains the entry point of your application. It initializes the web host and sets up the configuration, logging, and other services.

namespace MyFirstWebAPIProject
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseHttpsRedirection();

            app.UseAuthorization();


            app.MapControllers();

            app.Run();
        }
    }
}

As shown in the above Program class code, it has a public static void Main() method. The Main method is the entry point of our Application.

Each ASP.NET Core Web API Application initially starts as a Console Application and the Main() method is the entry point to the application. So, when we execute the ASP.NET Core Web API application, it first looks for the Main() method and this is the method from where the execution starts for the application. The Main() method then configures ASP.NET Core and starts it. At this point, the application becomes an ASP.NET Core Web API application.

Learn More about ASP.NET Core Main Method.

Startup.cs class file:

If you are working with the earlier version of .NET Core (less than .NET 6), then you will find the following Startup class which is like the Global.asax file of our traditional .NET application. As the name suggests, it is executed when the application starts. You will find the following code in your Startup class.

namespace MyFirstWebAPIProject
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "MyFirstWebAPIProject", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MyFirstWebAPIProject v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

As you can see in the above code, the Startup class includes two public methods: ConfigureServices and Configure.

ConfigureServices() method:

The ConfigureServices method of the Startup class is the place where we can register our dependent classes with the built-in IoC container. Once we register the dependent classes, they can be used anywhere within the application. The ConfigureServices method includes the IServiceCollection parameter to register services to the IoC container.

If you notice, currently it adds two services i.e. AddControllers and AddSwaggerGen to the built-in IoC Container as shown in the below image.

ConfigureServices() method in ASP.NET Core Web API

Configure() method:

The Configure method of the Startup class is the place where we configure the application request pipeline using the IApplicationBuilder instance that is provided by the built-in IoC container. ASP.NET Core introduced the middleware components to define a request pipeline, which will be executed on every request. If you look at the Configure method, it registered UseDeveloperExceptionPage, UseSwagger, UseSwaggerUI, UseHttpsRedirection, UseRouting, UseAuthorization, and UseEndpoints middleware components to the request processing pipeline as shown in the below image. We will discuss each middleware component in detail in our upcoming articles.

Configure() method in ASP.NET Core Web API

Learn more about the ASP.NET Core Startup class.

WeatherForecast.cs class file:

This is the model class and you can find the following code in it. This directory typically includes the data models or entities used by your application. These models represent the structure and shape of your data.

public class WeatherForecast
{
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    public string Summary { get; set; }
}

Note: The Model can be placed anywhere. It can be placed inside the Models folder. Directly at the project level. Even they can be created as separate class library projects.

[ProjectName].csproj:

This is the project file that defines the structure of your project, including its dependencies, build settings and references.

These are the most common files and directories you’ll encounter in an ASP.NET Core 6.0 Web API project. However, depending on your specific requirements and project setup, you may have additional files and directories.

In the next article, I am going to discuss Swagger API in ASP.NET Core Web API. Here, in this article, I try to Default Files and Folders of the ASP.NET Core Web API Project. I hope you enjoy this Default Files and Folders of the ASP.NET Core Web API Project article.

1 thought on “ASP.NET Core Web API Files and Folders”

Leave a Reply

Your email address will not be published. Required fields are marked *