1. Project Structure & Fundamentals

ASP.NET Core Fundamentals & Project Structure - Complete Guide

Practical Guide + Technical Reference


📋 Table of Contents

Part 1: Practical Guide (Hands-On)

  1. What is ASP.NET Core

  2. Getting Started - 3 Ways to Create a Project

  3. Project Structure Deep Dive

  4. .NET CLI Commands Reference

  5. Application Startup Lifecycle

  6. Environments

  7. Troubleshooting Common Issues

  8. Best Practices

Part 2: Technical Reference (Deep Dive)

  1. Important Classes & Interfaces Reference

  2. Configuration System Deep-Dive

  3. Hosting Models Details

  4. Advanced Topics


PART 1: PRACTICAL GUIDE


1. What is ASP.NET Core?

Simple Definition: A cross-platform, high-performance framework for building modern web applications and APIs.

Think of it like: The engine and chassis for your web application. You bring the design and business logic, ASP.NET Core provides the infrastructure.

Key Benefits

Cross-Platform - Runs on Windows, Linux, macOS ✅ High Performance - One of the fastest web frameworks ✅ Open Source - Free and community-driven ✅ Cloud-Ready - Built for Azure, AWS, Docker ✅ Modern - Supports latest C# features


.NET Evolution Timeline

LTS = Long-Term Support (3 years) Standard = Support for 18 months


.NET Framework vs .NET Core vs .NET 5+

Feature
.NET Framework
.NET Core
.NET 5+

Cross-Platform

❌ Windows only

✅ Win/Linux/Mac

✅ Win/Linux/Mac

Open Source

❌ No

✅ Yes

✅ Yes

Performance

Good

Better

Best

Side-by-side

❌ No

✅ Yes

✅ Yes

Future Support

❌ Maintenance

❌ EOL

✅ Active

When to Use

Legacy apps

❌ Use .NET 5+

✅ New projects

Recommendation: Use .NET 8.0 (LTS) for new projects (as of 2024-2025)


When to Use ASP.NET Core

✅ Perfect For:

  • REST APIs

  • Web APIs

  • Microservices

  • Real-time apps (SignalR)

  • Cloud-native applications

  • Docker containers

  • Cross-platform deployment

⚠️ Consider Alternatives:

  • Simple static websites → Consider static site generators

  • WordPress-style CMS → WordPress/Umbraco

  • Desktop apps → WPF, WinForms, MAUI


2. Getting Started - 3 Ways to Create a Project

Method 1: Visual Studio (Beginner-Friendly)

When to use:

  • ✅ New to .NET

  • ✅ Windows development

  • ✅ Like GUI tools

  • ✅ Integrated debugging

Step 1: Open Visual Studio

  • Launch Visual Studio 2022 (or later)

Step 2: Create New Project

  1. File → New → Project

  2. Search for "ASP.NET Core Web"

  3. Choose template:

    • ASP.NET Core Web API (REST APIs)

    • ASP.NET Core Web App (MVC) (Full websites)

    • ASP.NET Core Web App (Razor Pages) (Page-based apps)

    • Blazor (SPA with C#)

Step 3: Configure Project

Step 4: Run

  • Press F5 (or click "▶ MyFirstApi")

  • Browser opens to https://localhost:7xxx/swagger


When to use:

  • ✅ Quick project creation

  • ✅ Automation/scripts

  • ✅ VS Code users

  • ✅ Command-line preference

Step 1: Check .NET Installation

Step 2: Create Project

Step 3: Navigate and Run

Output:

Step 4: Test

  • Open browser: https://localhost:7148/swagger

  • Or use curl: curl https://localhost:7148/weatherforecast


Method 3: VS Code (Lightweight)

When to use:

  • ✅ Lightweight editor

  • ✅ Cross-platform development

  • ✅ Don't need full Visual Studio

  • ✅ Resource-constrained machine

Step 1: Install Prerequisites

Step 2: Create Project via Terminal

Step 3: Trust HTTPS Certificate (First time only)

Step 4: Run and Debug

  • Press F5

  • VS Code asks to add debug configuration → Yes

  • Creates .vscode/launch.json automatically

  • App starts with debugger attached


Template Comparison

Template
Use Case
Complexity
Output

webapi

REST APIs, microservices

Simple

JSON responses

mvc

Traditional websites

Medium

HTML views

razor

Page-focused apps

Simple-Medium

HTML pages

blazorserver

Interactive UIs (server)

Medium

C# + HTML

blazorwasm

SPA (runs in browser)

Medium-Complex

WebAssembly

empty

Start from scratch

Minimal

Nothing

Decision Tree:


3. Project Structure Deep Dive

Complete Folder Structure (Web API Project)


Program.cs - The Entry Point

ASP.NET Core uses different hosting models depending on version:

✨ .NET 6+ Minimal Hosting Model (Modern)

File: Program.cs

Key Points:

  • No Main method (it's implicit)

  • No Startup class (all in one file)

  • Clean and concise

  • Recommended for all new projects


Pre-.NET 6 Model (Legacy)

File: Program.cs

File: Startup.cs


Side-by-Side Comparison

Aspect
Minimal (.NET 6+)
Legacy (Pre-.NET 6)

Files

1 file (Program.cs)

2 files (Program.cs + Startup.cs)

Lines of Code

~15-20

~40-50

Complexity

Lower

Higher

Learning Curve

Easier

Steeper

When to Use

✅ New projects

❌ Legacy only

Recommendation: Always use Minimal Hosting Model (.NET 6+) for new projects


appsettings.json - Configuration

Purpose: Store application configuration (connection strings, API keys, settings)

Structure:


Environment-Specific Configuration

ASP.NET Core supports multiple configuration files:

Loading Order (Priority):


Reading Configuration (3 Methods)

Method 1: IConfiguration Directly (Simple)

When to use: Quick access, one-time reads


Method 2: GetSection (Medium)

When to use: Group related settings


Method 3: Strongly-Typed with IOptions (Recommended)

When to use: Production apps, type safety, testability

Step 1: Create Options Class

Step 2: Register in Program.cs

Step 3: Inject IOptions

Benefits:

  • ✅ Type safety (compile-time checking)

  • ✅ IntelliSense support

  • ✅ Easy testing (mock IOptions)

  • ✅ Validation support


wwwroot/ - Static Files

Purpose: Serve static files (CSS, JavaScript, images, fonts)

Default Structure:

Enable Static Files:

Accessing Files:

Custom Static File Directory:


.csproj - Project File

Purpose: Defines project settings, dependencies, build configuration

Example: MyFirstApi.csproj

Key Elements:

Element
Purpose
Example

Sdk

Project type

Microsoft.NET.Sdk.Web

TargetFramework

.NET version

net8.0

Nullable

Nullable reference types

enable

ImplicitUsings

Auto-import common namespaces

enable

PackageReference

NuGet packages

Swashbuckle.AspNetCore


Adding NuGet Packages (3 Methods)

Method 1: Visual Studio (GUI)

  1. Right-click project → Manage NuGet Packages

  2. Browse tab → Search "EntityFrameworkCore"

  3. Click Install

Method 2: .NET CLI (Recommended)

Method 3: Edit .csproj Manually

Then run:


Folder Conventions (Best Practices)

Key Principle: Separation of Concerns


4. .NET CLI Commands Reference

Essential Commands

Command
Purpose
Example

dotnet --version

Check .NET version

dotnet --version

dotnet --info

Detailed SDK info

dotnet --info

dotnet new

Create new project

dotnet new webapi -n MyApi

dotnet restore

Restore NuGet packages

dotnet restore

dotnet build

Compile project

dotnet build

dotnet run

Build and run

dotnet run

dotnet watch

Run with hot reload

dotnet watch run

dotnet test

Run tests

dotnet test

dotnet publish

Publish for deployment

dotnet publish -c Release

dotnet clean

Clean build artifacts

dotnet clean


Project Management


Package Management


Build & Run


Publishing


Entity Framework Core Commands


Development Helpers


5. Application Startup Lifecycle

Visual Flow Diagram


Detailed Startup Code


Builder Phase vs App Phase

Phase
Purpose
Examples

Builder Phase

Configure services

builder.Services.Add...

Set up DI

AddScoped<>, AddSingleton<>

Configure options

Configure<TOptions>()

Add authentication

AddAuthentication()

App Phase

Configure middleware

app.Use...

Set up HTTP pipeline

UseRouting(), UseAuthorization()

Map endpoints

MapControllers(), MapGet()

Start server

app.Run()


6. Environments

What are Environments?

Environments allow different configurations for Development, Staging, and Production.

Common Environments:

  • Development - Your local machine

  • Staging - Pre-production testing

  • Production - Live application


Setting the Environment

Method 1: Environment Variable

Windows (PowerShell):

Windows (Command Prompt):

Linux/macOS:


Method 2: launchSettings.json (Development)

File: Properties/launchSettings.json

Usage:


Method 3: Command Line


Environment-Specific Configuration Files

Example:

appsettings.json:

appsettings.Development.json:

appsettings.Production.json:


Checking Environment in Code


IWebHostEnvironment / IHostEnvironment


User Secrets (Development Only)

Purpose: Store sensitive data (API keys, passwords) outside source control

Step 1: Initialize User Secrets

This adds to .csproj:

Step 2: Add Secrets

Step 3: List Secrets

Step 4: Access in Code

Location:

  • Windows: %APPDATA%\Microsoft\UserSecrets\{UserSecretsId}\secrets.json

  • Linux/macOS: ~/.microsoft/usersecrets/{UserSecretsId}/secrets.json


7. Troubleshooting Common Issues

Issue 1: Port Already in Use

Symptom:

Solutions:

Option 1: Change Port

Option 2: Kill Process Using Port

Windows:

Linux/macOS:


Issue 2: HTTPS Certificate Not Trusted

Symptom:

Solution:

If that doesn't work:


Issue 3: Package Restore Failed

Symptom:

Solutions:


Issue 4: Startup Class Not Found (Pre-.NET 6)

Symptom:

Solution: Ensure Program.cs references Startup:


Issue 5: Configuration Not Loading

Symptom: Configuration values are null

Checklist:

  1. ✅ File named correctly: appsettings.json (case-sensitive on Linux)

  2. ✅ File copied to output: Right-click → Properties → Copy to Output Directory: "Copy if newer"

  3. ✅ JSON syntax valid (use JSON validator)

  4. ✅ Section names match exactly (case-sensitive)


Issue 6: Services Not Resolving

Symptom:

Solution: Ensure service is registered:


8. Best Practices

✅ Project Structure


✅ Configuration


✅ Dependency Injection


✅ Security


✅ Performance


✅ Logging


✅ Error Handling


✅ Code Quality


PART 2: TECHNICAL REFERENCE


9. Important Classes & Interfaces Reference

WebApplication Class

Namespace: Microsoft.AspNetCore.Builder

Purpose: Represents the configured web application (used in .NET 6+ minimal hosting)

Full Declaration:

Key Properties:

Property
Type
Description

Services

IServiceProvider

Access to dependency injection container

Configuration

IConfiguration

Application configuration

Environment

IWebHostEnvironment

Hosting environment info

Lifetime

IHostApplicationLifetime

Application lifetime events

Logger

ILogger

Logger instance

Urls

ICollection<string>

URLs the server is listening on

Key Methods:

Method
Return Type
Description

Run()

void

Runs application and blocks until shutdown

RunAsync()

Task

Runs application asynchronously

Start()

void

Starts application without blocking

StopAsync()

Task

Gracefully stops application

CreateBuilder(args)

WebApplicationBuilder

Creates builder (static)

Usage Example:


WebApplicationBuilder Class

Namespace: Microsoft.AspNetCore.Builder

Purpose: Builder for configuring services and the application pipeline

Full Declaration:

Key Properties:

Property
Type
Description

Services

IServiceCollection

Service collection for DI

Configuration

ConfigurationManager

Configuration builder

Environment

IWebHostEnvironment

Environment information

Host

ConfigureHostBuilder

Host configuration

WebHost

ConfigureWebHostBuilder

Web host configuration

Logging

ILoggingBuilder

Logging configuration

Key Methods:

Method
Return Type
Description

Build()

WebApplication

Builds the web application

Usage Example:


IWebHostEnvironment Interface

Namespace: Microsoft.AspNetCore.Hosting

Purpose: Provides information about the web hosting environment

Full Declaration:

Inherited from IHostEnvironment:

Property
Type
Description

EnvironmentName

string

Environment name (Development, Production, etc.)

ApplicationName

string

Application name

ContentRootPath

string

Path to application content files

ContentRootFileProvider

IFileProvider

File provider for content root

Extension Methods:

Method
Description

IsDevelopment()

True if environment is "Development"

IsProduction()

True if environment is "Production"

IsStaging()

True if environment is "Staging"

IsEnvironment(string env)

True if environment matches

Usage Example:


IConfiguration Interface

Namespace: Microsoft.Extensions.Configuration

Purpose: Represents configuration from various sources

Full Declaration:

Key Methods:

Method
Description

this[string key]

Get/set value by key

GetSection(string key)

Get configuration section

GetChildren()

Get child sections

GetConnectionString(string name)

Get connection string

GetValue<T>(string key)

Get strongly-typed value

GetValue<T>(string key, T defaultValue)

Get value with default

Extension Methods:

Method
Description

Bind(object instance)

Bind configuration to object

Get<T>()

Get strongly-typed configuration

Exists()

Check if section exists

Usage Example:


ConfigurationManager Class ✨ .NET 6.0+

Namespace: Microsoft.Extensions.Configuration

Purpose: Combines configuration builder and configuration in one

Full Declaration:

Key Methods:

Method
Return Type
Description

AddJsonFile(path)

IConfigurationBuilder

Add JSON configuration file

AddEnvironmentVariables()

IConfigurationBuilder

Add environment variables

AddCommandLine(args)

IConfigurationBuilder

Add command-line args

AddUserSecrets<T>()

IConfigurationBuilder

Add user secrets

Build()

IConfigurationRoot

Not needed, already built

Usage Example:


IServiceCollection Interface

Namespace: Microsoft.Extensions.DependencyInjection

Purpose: Collection of service descriptors for dependency injection

Full Declaration:

Extension Methods (Common):

Method
Description

AddTransient<TService, TImplementation>()

Register transient service

AddScoped<TService, TImplementation>()

Register scoped service

AddSingleton<TService, TImplementation>()

Register singleton service

AddTransient<TService>()

Register concrete type as transient

Configure<TOptions>(Action<TOptions>)

Configure options

AddOptions<TOptions>()

Add options services

Usage Example:


IServiceProvider Interface

Namespace: System

Purpose: Service locator for retrieving services

Full Declaration:

Extension Methods:

Method
Description

GetService<T>()

Get service (returns null if not found)

GetRequiredService<T>()

Get service (throws if not found)

GetServices<T>()

Get all services of type

CreateScope()

Create new service scope

Usage Example:


10. Configuration System Deep-Dive

Configuration Sources

ASP.NET Core loads configuration from multiple sources in order:

Later sources override earlier sources


Adding Custom Configuration Sources


Configuration Providers

Provider
Package
Usage

JSON

Built-in

AddJsonFile()

Environment Variables

Built-in

AddEnvironmentVariables()

Command Line

Built-in

AddCommandLine()

User Secrets

Built-in

AddUserSecrets<T>()

XML

Microsoft.Extensions.Configuration.Xml

AddXmlFile()

INI

Microsoft.Extensions.Configuration.Ini

AddIniFile()

Azure Key Vault

Azure.Extensions.AspNetCore.Configuration.Secrets

AddAzureKeyVault()

Azure App Configuration

Microsoft.Extensions.Configuration.AzureAppConfiguration

AddAzureAppConfiguration()


Strongly-Typed Configuration (IOptions)

Pattern 1: IOptions (Singleton)

When to use: Configuration that doesn't change during application lifetime


Pattern 2: IOptionsSnapshot (Scoped)

When to use: Configuration that might change between requests


Pattern 3: IOptionsMonitor (Singleton with Live Reload)

When to use: Configuration that changes at runtime (live reload)


IOptions Comparison Table

Feature

IOptions

IOptionsSnapshot

IOptionsMonitor

Lifetime

Singleton

Scoped

Singleton

Reload

❌ No

✅ Per request

✅ Live

DI Support

All

Scoped/Transient only

All

Performance

Fastest

Medium

Medium

Use Case

Static config

Per-request config

Live config


Configuration Binding

Simple Binding:


Complex Binding (Nested Objects):


Array Binding:


Configuration Validation ✨ .NET 6.0+


11. Hosting Models Details

Kestrel (Cross-Platform Web Server)

Default web server - Written in C#, runs on all platforms

Basic Configuration:


IIS Integration (Windows)

Hosting Models:

In-Process (Recommended)

  • Runs inside IIS worker process (w3wp.exe)

  • Better performance

  • Single process

Out-of-Process

  • IIS proxies to Kestrel

  • Two processes

  • Easier debugging


Reverse Proxy Patterns

Production Setup:

Nginx Configuration Example:

ASP.NET Core Configuration:


12. Advanced Topics

Custom Application Lifetime Events


Generic Host vs Web Host

.NET 6+ uses Generic Host (recommended)

Benefits:

  • Unified hosting model

  • Works for web, console, background services

  • Better dependency injection


Background Services


Minimal APIs ✨ .NET 6.0+

Simple REST API without controllers:


Performance Tips

1. Use Response Compression

2. Enable Response Caching

3. Optimize Static Files

4. Use Output Caching ✨ .NET 7.0+


Summary: Complete Fundamentals Checklist

✅ Getting Started

✅ Project Structure

✅ Configuration

✅ Dependency Injection

✅ Environments

✅ Best Practices


This completes the ASP.NET Core Fundamentals & Project Structure guide combining practical hands-on content with deep technical reference!

Last updated