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:

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

Folders and Files in ASP.NET Core Web API

Now, let us proceed and understand the above files and folders in detail.

Dependencies:

The Dependencies folder contains 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

Here’s a brief overview of what each of these folders typically contains:

Analyzers:

This folder includes static code analyzers that are integrated into your project. Analyzers examine your code for style, quality, maintainability, design, and other issues.

  • Static Code Analysis: Analyzers perform static code analysis, which means they analyze your code without actually executing it. This analysis occurs as you write your code, offering real-time feedback and suggestions within your IDE (like Visual Studio).
  • Coding Standards and Style Enforcement: They help enforce coding standards and styles. This includes ensuring adherence to naming conventions, layout rules, and best practices that are generally accepted in the .NET community or specific to your organization.
  • Identify Common Coding Issues and Bugs: Analyzers can detect common coding mistakes and potential bugs. For example, they can identify code that may lead to null reference exceptions, improper disposal of objects, or inefficient use of resources.
  • Performance Optimization: Some analyzers are designed to highlight areas where code performance can be improved, such as inefficient loops, unnecessary allocations, or other resource-intensive operations.
  • Refactoring and Code Improvement Suggestions: Analyzers can suggest refactorings or improvements to make the code more readable, maintainable, or efficient. They can propose using newer language features or more appropriate design patterns.
  • Dependency and Package Management: Some analyzers focus on dependencies and package management, ensuring that you’re using the correct versions of NuGet packages and highlighting potential compatibility issues.
  • Framework-Specific Guidelines: In the context of ASP.NET Core Web API, analyzers can provide recommendations and checks specific to web development, such as proper handling of HTTP requests and responses, API design guidelines, and best practices for middleware configuration.
Frameworks:

Here, you will find the .NET Core Frameworks that your project depends on. These packages are essential for running and building ASP.NET Core applications. This includes the base .NET Core libraries and any specific ASP.NET Core libraries necessary for your Web API project. The framework contains two folders, i.e., Microsoft.AspNetCore.App and Microsoft.NETCore.App.

  • Microsoft.AspNetCore.App: This package (or folder) contains the essential libraries and components needed for building and running ASP.NET Core applications, including Web APIs. It includes the ASP.NET Core framework, middleware, and various utility libraries.
  • Microsoft.NETCore.App: This package (or folder) contains the runtime components necessary for running .NET Core applications, including ASP.NET Core applications. Microsoft.NETCore.App provides the core runtime environment and common libraries that are required for any .NET Core application to execute. It includes things like the Common Language Runtime (CLR) and base class libraries.
Packages:

This folder includes NuGet packages that your project depends on. NuGet packages can provide additional functionality, libraries, or tools that are not part of the standard .NET Core Frameworks. Common packages in ASP.NET Core Web API projects might include libraries for JSON serialization, database connectivity (like Entity Framework Core), logging frameworks, or third-party integrations.

Currently, the Packages folder contains one package, i.e., Swashbuckle.AspNetCore. If you remember, when we ran the application, then it opened 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.

Properties:

By default, the Properties Folder in the ASP.NET Core Web API Application contains one JSON file called launchsettings.json file. This launchsettings.json file contains configuration settings for launching the application, such as environment variables and application URLs that will be used by .NET Core Framework when we run the application either from Visual Studio or by using .NET Core CLI. Another point you need to remember is that the launchSettings.json file is only used within the local development machine. So, this file will not be required when we publish our ASP.NET Core Web API application on the production server. Now, open the launchSettings.json file; by default, you will see the following settings.

{
  "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"
      }
    },
    "WSL": {
      "commandName": "WSL2",
      "launchBrowser": true,
      "launchUrl": "https://localhost:7237/swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development",
        "ASPNETCORE_URLS": "https://localhost:7237;http://localhost:5222"
      },
      "distributionName": ""
    }
  },
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:1064",
      "sslPort": 44312
    }
  }
}

As shown in the above file, we can use four launch settings to launch our application. They are as follows:

  • HTTP
  • HTTPS
  • IIS Expression
  • WSL

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. By default, you will get the following settings in the launchsettings.json file for HTTP Profile:

HTTP Profile

HTTPS Profile:

These settings determine the URLs and ports on which your application will listen for incoming HTTPS requests. 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

WSL Profile:

If you are developing on Windows but targeting a Linux environment, you need to use WSL. The WSL profile in launchSettings.json allows you to run and debug your application in a Linux-like environment. By default, you will get the following settings in the launchsettings.json file for WSL Profile:

WSL Profile

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

Now, let us proceed and understand the different parameters used in the above settings:

applicationUrl:
  • Specifies the URLs on which the application will listen for incoming HTTP/HTTPS requests.
  • Example: “applicationUrl”: “https://localhost:7237;http://localhost:5222”
  • This means the application will be accessible at http://localhost:5222 and https://localhost:7237.
environmentVariables:
  • Sets environment variables for the application when the profile is used.
  • Example: “environmentVariables”: { “ASPNETCORE_ENVIRONMENT”: “Development” }
  • This sets the ASPNETCORE_ENVIRONMENT to Development, enabling development-specific features like detailed error pages. Other possible values are Production, Staging
commandName:
  • Indicates the command to execute the application.
  • Common values are “Project”, which runs the project directly using Kestrel, or “IISExpress” for launching with IIS Express
  • Example: “commandName”: “Project”
launchBrowser:
  • Determines whether a web browser should be automatically opened to the application URL when the application starts.
  • Example: “launchBrowser”: true
  • When set to true, a browser window will open and navigate to the application URL upon startup.
launchUrl:
  • Specifies the specific URL or endpoint to open in the browser when launchBrowser is set to true.
  • Example: “launchUrl”: “swagger”
  • This could open the Swagger UI for API documentation if Swagger is configured in the project.
sslPort:
  • If your application supports HTTPS, this setting specifies the SSL port to be used.
  • Example: “sslPort”: 44312
  • The application will listen for HTTPS requests on this port.
dotnetRunMessages:
  • Determines whether or not to show messages from the dotnet run command.
  • Example: “dotnetRunMessages”: “true”
windowsAuthentication:
  • This parameter is used primarily in the context of IIS or IIS Express.
  • It’s a boolean value (true or false) indicating whether Windows Authentication is enabled or not.
  • When enabled (“windowsAuthentication”: true), the application will use Windows Authentication to authenticate users. This is often used in intranet environments where users are authenticated via their Windows domain accounts.
anonymousAuthentication:
  • Similar to windowsAuthentication, this is also typically used with IIS or IIS Express.
  • It’s a boolean value that enables or disables anonymous authentication.
  • When enabled (“anonymousAuthentication”: true), users can access the application without any authentication. This is common for public-facing web applications.
ASPNETCORE_URLS:
  • This is an environment variable used to specify the URLs the application should listen on.
  • It overrides the applicationUrl setting in launchSettings.json.
  • Example: “ASPNETCORE_URLS”: “https://localhost:7237;http://localhost:5222”
  • This tells the application to listen for HTTP requests on port 5222 and HTTPS requests on port 7237.
distributionName:
  • This parameter is relevant when using Windows Subsystem for Linux (WSL) as a development environment.
  • It specifies the name of the Linux distribution you want to use with WSL.
  • Example: “distributionName”: “Ubuntu-20.04”
  • This would mean the application will run using Ubuntu 20.04 in WSL.

Controllers Folder:

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 inside the Controllers folder, called WeatherForecastController, with the following code:

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();
        }
    }
}

As you can see in the above code, the Controller class is inherited from the ControllerBase class and decorated with ApiController and Route attributes. As you can see in the above code, we have one Get method decorated with the HttpGet attribute. This method will return the data when we call the following URL using any client (Swagger, Postman, Fiddler, and Browser). We will discuss the Controller in detail in our upcoming sessions.

https://localhost:7237/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 Framework Application. The appsettings.json file is the application configuration file in the ASP.NET Core Web Application used to store the configuration settings for your application, such as database connection strings, API keys, and logging settings.

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.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}
Structure and Usage
  • JSON Format: The appsettings.json file is structured as a JSON object, making it easy to read and edit.
  • Hierarchical Configuration Data: Settings are often structured hierarchically. For instance, database connection strings, logging settings, or custom application settings can be organized into separate sections or objects.
  • Environment-Specific Files: In addition to appsettings.json, you can have environment-specific files like appsettings.Development.json, appsettings.Staging.json, or appsettings.Production.json. These files can override settings in appsettings.json based on the environment the application is running in.

MyFirstWebAPIProject.http file

The .http file, in an ASP.NET Core Web API project, is a feature provided by certain Integrated Development Environments (IDEs) like JetBrains Rider or Visual Studio Code, Visual Studio with the REST Client extension. These files are used to test HTTP requests directly from the IDE. This feature is particularly useful for testing and debugging APIs. You will find the following code in the MyFirstWebAPIProject.http file.

@MyFirstWebAPIProject_HostAddress = http://localhost:5222

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

###
Structure
  • HTTP Requests: The file contains plain HTTP requests, which you can run directly from the IDE.
  • Syntax: It uses a simple syntax to define HTTP methods, URLs, headers, and body content.
  • Multiple Requests: You can define multiple requests in a single file, separated by a line of ###.
How to Use?

First, run the application using the 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:

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

Advantages
  • Convenience: Allows you to test API endpoints directly from the IDE without needing an external tool like Postman or Fiddler.
  • Version Control: This can be checked into source control, allowing team members to share and collaborate on API tests.
  • Documentation: Serves as a form of documentation of the API endpoints and their usage.

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.

Program.cs Class File:

In a .NET 8 project, the Program.cs file is the entry point of the application. It is where the execution begins for a .NET application. Starting with .NET 6 and continuing with .NET 8, the default template for ASP.NET Core projects uses a more simplified structure for the Program.cs file, adopting a minimal hosting model. If you open the Program.cs class file, then you will find the following code by default:

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();
        }
    }
}
Creating and Building the Web Application:

The application starts with creating a WebApplicationBuilder instance, which is used to set up the app’s hosting and configuration. This builder is used to set up services and configuration.

var builder = WebApplication.CreateBuilder(args);

Adding Services to the DI Container:

Services required by the app, like MVC, Web API, Entity Framework, custom services, etc., are registered with the dependency injection (DI) container. Services are added to the DI container using the builder.Services.Add… methods. AddControllers() is typically used for a Web API to add support for controllers and API-related features.

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

Here,

AddEndpointsApiExplorer: The AddEndpointsApiExplorer() method is used to enable API Explorer services required for generating the OpenAPI specification. This method adds services necessary for discovering endpoint metadata. This metadata is essential for tools like Swagger to generate accurate and useful documentation for your Web API.

AddSwaggerGen: The AddSwaggerGen() method adds Swagger generator services to the project. These services are responsible for generating Swagger documents, which describe the structure and capabilities of your Web API. This method allows for customization of the Swagger documentation, such as setting the title and version and even adding custom descriptions and schemas.

Configuring the HTTP Request Pipeline:

After building the app, you need to configure the HTTP request pipeline by adding middleware components. The builder.Build() creates an instance of WebApplication, which is used to set up the middleware pipeline. The app.Use… methods are used to add middleware to the application’s request pipeline. This includes error handling, redirection to HTTPS, static file serving, routing, and authorization.

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();
Running the Application:

Finally, the Run method starts the app.

app.Run();

Note: The traditional Startup.cs file is no longer needed. The Program.cs file now contains what used to be in both Program.cs and Startup.cs.

WeatherForecast.cs class file:

This is the model class; you can find the following code. The model represents the structure and shape of your data.

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; }
    }
}

Note: The Model can be placed anywhere. It can be placed inside the Models folder or directly at the project level. They can even be created as separate class library projects.

These are the most common files and directories you will encounter in an ASP.NET Core Web API project when created using Visual Studio and .NET 8. However, depending on your specific requirements and project setup, you may have additional files and directories.

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 *