Default ASP.NET Core Web API Files and Folders

Default ASP.NET Core Web API Files and Folders

In this article, I will discuss the Default ASP.NET Core Web API Files and Folders, i.e., those created by default when we create a new ASP.NET Core Web API Application. Please read our previous article discussing How to Create, Build, and Run ASP.NET Core Web API in Visual Studio 2022 using .NET 8.

Folders and Files in ASP.NET Core Web API:

When we create a new ASP.NET Core Web API project using Visual Studio 2022 and .NET 8, it generates a set of default files and folders. Understanding the file and folder structure is crucial for effective development and maintenance. We have created an ASP.NET Core Web API project using Visual Studio 2022 in our previous article, which comes with a predefined set of files and folders that form the foundation of a Web API application, as shown in the image below.

Folders and Files in ASP.NET Core Web API

Let’s proceed and understand what these files and folders do and why they’re essential.

Connected Services

The Connected Services node in Solution Explorer allows us to integrate external services into our project easily. These services can include:

  • Azure services (e.g., Azure Storage, Azure App Services).
  • Third-party REST APIs (e.g., Google APIs, Stripe).
  • Microsoft Office 365 APIs for accessing Office 365 resources.

It simplifies consuming these services by automatically managing configurations, generating client code, and managing dependencies. For example, Azure Key Vault can be added to manage secrets through Connected Services.

Dependencies:

The Dependencies folder in Solution Explorer lists all the installed packages, SDKs, and libraries required for the project. Further, if you expand, it contains three files (Analyzers, Frameworks, and Packages), as shown in the below image.

Dependencies

Let us proceed and understand what each of these folders typically contains:

Analyzers

Analyzers are tools that analyze your code for potential issues like syntax errors, style violations, adherence to coding standards, or performance problems. They provide real-time feedback directly within the IDE, helping maintain high code quality. The following are some of the common use cases:

  • Code Quality Checks: Identifying bugs and warnings.
  • Style Enforcement: Ensuring consistent coding styles across the project.
  • Performance Suggestions: Recommending optimizations for better performance.
Frameworks

The Frameworks section lists the core libraries and runtime components your project depends on. For an ASP.NET Core Web API, this includes essential frameworks required for the application to function correctly.

Microsoft.NETCore.App:

This includes the .NET runtime, Base Class Libraries (BCL), Garbage Collector, JIT compiler, and other core functionality required to run .NET applications.

  • Base Class Libraries (BCL): Fundamental libraries like System.IO (file handling), System.Collections (collections), System.Threading (multi-threading), etc., providing essential programming functionalities.
  • Core Runtime Libraries: Includes the garbage collector, JIT compiler, and other runtime services necessary for executing .NET Core applications.
Microsoft.AspNetCore.App:

Contains ASP.NET Core libraries and features such as MVC, Razor, Kestrel, IIS integration, controllers, routing, model binding, and more. It provides APIs for building web applications, authentication, and authorization.

  • Web Server Implementations: Libraries for Kestrel and IIS integration, enabling your application to handle HTTP requests.
  • ASP.NET Core MVC: Framework components supporting the Model-View-Controller architecture for building robust web applications.
  • Razor Engine: Processes Razor pages and views for dynamic content generation.
  • API-Related Libraries: Features for building APIs, including controllers, routing, model binding, and more.
  • Authentication and Authorization Libraries: Components necessary for securing your web applications.
Packages

The Packages folder contains all external NuGet packages your project utilizes. These packages provide additional functionalities and can be easily managed via the NuGet Package Manager. By default, you might see Swashbuckle.AspNetCore is used to generate interactive API documentation that is accessible via Swagger UI. The following are some of the commonly used Packages:

  • Swashbuckle.AspNetCore: Enables Swagger UI integration for API documentation and testing.
  • Entity Framework Core: Facilitates database access and management.
  • Serilog/NLog: Provides advanced logging capabilities.
  • IdentityServer: Handles authentication and authorization mechanisms.

Note: Packages can be added or removed using the NuGet Package Manager in Visual Studio as the project evolves.

Properties:

The Properties folder primarily contains configuration files that define how your application behaves during development and deployment. By default, the Properties folder in an ASP.NET Core Web API project includes a single file: launchSettings.json.

launchSettings.json

The launchSettings.json file Stores local development launch configurations, including environment variables, application URLs, and profiles that tell how the application starts. This configuration is utilized by Visual Studio and the .NET Core CLI during development. This file is not used in production. When we deploy our application into production, these local launch profiles are no longer needed. Now, open the launchSettings.json file; by default, you will see the following settings.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"profiles": {
"http": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "http://localhost:5222"
},
"https": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7237;http://localhost:5222"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:1064",
"sslPort": 44312
}
}
}
{ "profiles": { "http": { "commandName": "Project", "launchBrowser": true, "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "dotnetRunMessages": true, "applicationUrl": "http://localhost:5222" }, "https": { "commandName": "Project", "launchBrowser": true, "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" }, "dotnetRunMessages": true, "applicationUrl": "https://localhost:7237;http://localhost:5222" }, "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "swagger", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, }, "$schema": "http://json.schemastore.org/launchsettings.json", "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:1064", "sslPort": 44312 } } }
{
  "profiles": {
    "http": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "dotnetRunMessages": true,
      "applicationUrl": "http://localhost:5222"
    },
    "https": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "dotnetRunMessages": true,
      "applicationUrl": "https://localhost:7237;http://localhost:5222"
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:1064",
      "sslPort": 44312
    }
  }
}

Within this file, you’ll commonly see three launch profiles:

  1. http – Configures the app to run over HTTP.
  2. https – Configures the app to run over HTTPS, usually involving a development SSL certificate.
  3. IIS Express – Runs your app in IIS Express, a lightweight version of IIS for development.

Let us understand each of these launch profile settings in detail.

HTTP Profile:

These settings determine the URLs and ports on which your application will listen for incoming HTTP requests when you launch the application using an HTTP profile from Visual Studio. By default, you will get the following settings in the launchsettings.json file for HTTP Profile:

HTTP Profile

Default Settings:
  • Application URL: http://localhost:5222
  • Launch URL: swagger (opens Swagger UI upon launch)
  • Environment: Development

Note: It is ideal for testing API endpoints without HTTPS. Suitable for local development scenarios where secure communication isn’t required.

HTTPS Profile:

These settings determine the URLs and ports on which your application will listen for incoming HTTP requests when you launch the application using the HTTPS profile from Visual Studio. The HTTPS setting usually includes an SSL certificate for secure communication. ASP.NET Core supports automatically generating a development-time SSL certificate for this purpose. By default, you will get the following settings in the launchsettings.json file for HTTPS Profile:

HTTP Profile

Default Settings:
  • Application URLs: https://localhost:7237 (secure) and http://localhost:5222 (optional non-secure)
  • Launch URL: swagger
  • Environment: Development

Note: We need to use this profile when testing secure endpoints or when our application requires HTTPS.

IIS Express Profile:

IIS Express is a lightweight, self-contained version of IIS optimized for development. By default, you will get the following settings in the launchsettings.json file for the IIS Express Profile:

IIS Express Profile

And for IIS Express, it will use the following settings:

Default ASP.NET Core Web API Files and Folders

Default Settings:
  • Application URL: Defined under iisSettings (e.g., http://localhost:1064)
  • SSL Port: 44312
  • Launch URL: swagger
  • Environment: Development

Note: We need to use this launch profile when we want to test our application in an environment similar to the production IIS server.

Controllers Folder:

ASP.NET Core Web API follows a Controller-based approach. The Controllers folder is the heart of our ASP.NET Core Web API application. It contains controller classes that handle incoming HTTP requests, execute business logic, and return appropriate HTTP responses.

  • Each controller typically represents a specific resource or a collection of related endpoints.
  • Controllers use routing attributes to map HTTP requests to action methods.
  • Controllers define Action Methods to define the operations (e.g., GET, POST, PUT, DELETE) performed on the resources.

By default, a sample controller named WeatherForecastController is included to demonstrate basic API functionality with the following code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
using Microsoft.AspNetCore.Mvc;
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(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
using Microsoft.AspNetCore.Mvc; 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(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } } }
using Microsoft.AspNetCore.Mvc;

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(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}
Code Explanations:

Let us understand the above code:

Attributes:
  • [ApiController]: Indicates that the class is an API controller, enabling features like automatic model validation and binding.
  • [Route(“[controller]”)]: Sets the base route for the controller, where [controller] is replaced by the controller’s name (e.g., “WeatherForecast”).
Constructor Injection:
  • Injects an ILogger<WeatherForecastController> instance for logging purposes.
Action Method:
  • [HttpGet(Name = “GetWeatherForecast”)]: Specifies that the Get method handles HTTP GET requests and assigns a route name for URL generation.
  • Functionality: Returns a collection of WeatherForecast objects with randomly generated data.
Accessing the Endpoint:

Once the application runs, you can access the endpoint via https://localhost:{port}/WeatherForecast using any client (Swagger, Postman, Fiddler, and Browser). You need to replace {port} with the actual port number specified in launchSettings.json.

appsettings.json file:

The appsettings.json file serves as the primary configuration source for our application. It stores various application settings such as connection strings, API keys, logging, and custom configurations. It supports hierarchical data structures and can be overridden by environment-specific files. For example, we can have environment-specific versions (e.g., appsettings.Development.json, appsettings.Production.json) that override settings in the base appsettings.json.

If you open the appsettings.json file, you will see the following code by default, created by Visual Studio when we created the ASP.NET Core Web API Application.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*" }
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}
Code Explanations:
  • Logging: Configures the logging levels for different parts of the application. For example, general logs are set to “Information,” while logs from Microsoft.AspNetCore is set to “Warning.”
  • AllowedHosts: Specifies which hosts are allowed to access the application. The wildcard “*” permits all hosts, which is suitable for development but should be restricted in production.
Program.cs Class File:

The Program.cs class file serves as the entry point of our ASP.NET Core Web API application. It sets up the web host, configures services, and defines the middleware pipeline that handles HTTP requests and responses. The following are the key Responsibilities:

  • Build and configure the ASP.NET Core host.
  • Register services (e.g., controllers, Swagger, etc.).
  • Define the middleware pipeline (e.g., app.UseHttpsRedirection();, app.UseAuthorization();, app.MapControllers();).
  • Start the application with the app.Run();

If you open the Program.cs class file, then you will find the following code by default:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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();
}
}
}
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(); } } }
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();
        }
    }
}
Service Registration:
  • AddControllers(): Registers MVC controllers with the dependency injection (DI) container.
  • AddEndpointsApiExplorer(): Enables API endpoint discovery, which is required for tools like Swagger.
  • AddSwaggerGen(): Registers services required to generate Swagger/OpenAPI documentation.
Middleware Configuration:
  • app.UseSwagger(): Generates Swagger JSON documentation.
  • app.UseSwaggerUI(): Serves the Swagger UI for interactive API exploration.
  • app.UseHttpsRedirection(): Redirects HTTP requests to HTTPS.
  • app.UseAuthorization(): Adds authorization middleware to enforce security policies.
  • app.MapControllers(): Maps controller routes to the request pipeline.

Note: You can add additional services (e.g., Entity Framework, Authentication) and middleware as your application requirements grow, such as authentication, CORS policies, exception handling, and more, to handle requests and responses. You can also modify the order of the middleware components.

WeatherForecast.cs class file:

The WeatherForecast.cs is a model class that defines the structure of the data returned by the WeatherForecastController. Models represent the shape of our data and are essential for data binding and validation. By default, the WeatherForecast model is created with the following structure:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
namespace MyFirstWebAPIProject
{
public class WeatherForecast
{
public DateOnly Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string? Summary { get; set; }
}
}
namespace MyFirstWebAPIProject { public class WeatherForecast { public DateOnly Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string? Summary { get; set; } } }
namespace MyFirstWebAPIProject
{
    public class WeatherForecast
    {
        public DateOnly Date { get; set; }

        public int TemperatureC { get; set; }

        public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);

        public string? Summary { get; set; }
    }
}
Properties:
  • Date: The date of the weather forecast.
  • TemperatureC: Temperature in Celsius.
  • TemperatureF: Read-only property that converts Celsius to Fahrenheit.
  • Summary: A brief description of the weather conditions.

Note: For better organization and maintainability, especially in larger projects, consider placing model classes within a dedicated “Models” folder or in a separate class library project.

MyFirstWebAPIProject.http file

The .http file provides a convenient way to test and debug HTTP requests directly within the IDE. This file utilizes the HTTP Client feature in Visual Studio, allowing us to send requests and view responses without external tools like Postman or Fiddler. You will find the following code in the MyFirstWebAPIProject.http file by default.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
@MyFirstWebAPIProject_HostAddress = http://localhost:5222
GET {{MyFirstWebAPIProject_HostAddress}}/weatherforecast/
Accept: application/json
###
@MyFirstWebAPIProject_HostAddress = http://localhost:5222 GET {{MyFirstWebAPIProject_HostAddress}}/weatherforecast/ Accept: application/json ###
@MyFirstWebAPIProject_HostAddress = http://localhost:5222

GET {{MyFirstWebAPIProject_HostAddress}}/weatherforecast/
Accept: application/json

###
How to Use?

Make sure your project is running (typically on an HTTP profile). Please ensure the port number used to launch the application using the HTTP profile and the port number used in the .http file must be the same.

Once the application is running, then open the MyFirstWebAPIProject.http file and Click on the “Send Request” link that appears above the HTTP request in the IDE as shown in the below image in Visual Studio to see the response immediately:

Default ASP.NET Core Web API Files and Folders

Once you click on the Send Request link, the responses are typically shown in a pane next to the request or in a separate window, allowing you to view the status code, response body, and headers, as shown in the image below.

Default ASP.NET Core Web API Files and Folders

Note: As we progress in this course, we will see how to perform GET, POST, PUT, PATCH, and DELETE requests using this .http file to test our APIS.

Understanding the default structure of an ASP.NET Core Web API project is fundamental to building robust and maintainable applications. Each folder and file serve a specific purpose, from managing dependencies and configurations to handling HTTP requests and defining data models.

These files and folders together form the backbone of an ASP.NET Core Web API project. As we develop our application, we will add more controllers, models, services, and configuration files to meet our requirements. However, understanding the function of each default file and folder helps us maintain a clean structure and a clear development workflow.

In the next article, I will discuss Swagger API in ASP.NET Core Web API. 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 “Default ASP.NET Core Web API Files and Folders”

Leave a Reply

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