Wednesday, August 13, 2025

Importance of Program.cs

 Example:

var builder = WebApplication.CreateBuilder(args);

// Add services

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();

builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure middleware

if (app.Environment.IsDevelopment())

{

    app.UseSwagger();

    app.UseSwaggerUI();

}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

This file defines how the app starts, loads middleware, and sets up endpoints.


Understanding Project Folder and File Structure

 Example default structure:

MyFirstApi/

│   Program.cs

│   MyFirstApi.csproj


├── Controllers/

│    WeatherForecastController.cs


├── Properties/

│    launchSettings.json


├── appsettings.json

└── appsettings.Development.json


Program.cs → Application startup configuration.

Controllers/ → Contains API endpoints.

appsettings.json → Configuration file.

launchSettings.json → Environment and profile settings.

Creating a New ASP.NET Core Web API Project

 Using Visual Studio:

  1. Open Visual Studio → "Create a new project".

  2. Select ASP.NET Core Web API.

  3. Configure project name & location.

  4. Choose .NET 8 (or latest).

Using Command Line:

dotnet new webapi -n MyFirstApi

cd MyFirstApi

dotnet run

Installing .NET SDK and IDEs

 

Install .NET SDK

Choose an IDE

  1. Visual Studio (Windows/Mac)

    • Best for beginners & large projects.

  2. Visual Studio Code (Cross-platform)

    • Lightweight, flexible.

    • Install C# extension.

Overview of ASP.NET Core and Web API Architecture?

 ASP.NET Core follows a middleware pipeline:

  1. Request → Middleware (Authentication, Logging, etc.) → Controller → Response

  2. Lightweight, modular design.

  3. Built-in dependency injection.

Architecture Diagram:

[Client] → [HTTP Server (Kestrel/IIS)] → [Middleware Pipeline] → [Controller] → [Data Access Layer] → [Database]


Why Use ASP.NET Core for Web APIs?

 ASP.NET Core offers:

  • Cross-platform support (Windows, Linux, macOS).

  • High performance (among the fastest web frameworks).

  • Dependency Injection built-in.

  • Unified MVC & API development model.

  • Security (Authentication, Authorization, Data Protection).

  • Integrated Swagger support for API documentation.

Common Use Cases:

  • E-commerce backend APIs.

  • Mobile app data services.

  • Microservices communication.

  • Real-time services with SignalR.

Importance of Program.cs

 Example: var builder = WebApplication.CreateBuilder(args); // Add services builder.Services.AddControllers(); builder.Services.AddEndpoints...