A comprehensive, production-ready .NET 9 Web API template with industry best practices, designed to accelerate your development process and provide a solid foundation for scalable applications.
- Clean Architecture with organized project structure
- Service Layer Pattern for business logic separation
- Repository Pattern ready for data access abstraction
- Dependency Injection with built-in .NET DI container
- Entity Framework Core 9 with SQL Server support
- Comprehensive CRUD Operations with sample entities
- API Versioning with multiple versioning strategies
- Swagger/OpenAPI 3.0 documentation with XML comments
- Request/Response Validation with Data Annotations
- Standardized Error Handling with proper HTTP status codes
- Health Checks for monitoring and diagnostics
- Environment Variable Support with strongly-typed configuration
- Multiple Environment Configurations (Development, Staging, Production)
- CORS Configuration for cross-origin requests
- Flexible Connection String Management
- Comprehensive .env.example with all settings documented
- Serilog Integration with structured logging
- Multiple Log Sinks (Console, File, Seq support)
- Performance Logging with slow request detection
- Request/Response Logging with customizable enrichment
- Environment-Specific Log Levels
- Log File Rotation and retention policies
- Entity Framework Core 9 with Code-First approach
- Database Migrations with comprehensive scripts
- Connection Retry Policies for resilience
- Database Health Checks
- Automatic Database Creation and seeding
- Cross-platform Database Scripts (Unix & Windows)
- Multi-stage Docker Build for optimized images
- Docker Compose configurations for development and production
- Security Best Practices (non-root user, minimal base image)
- Health Check Integration
- Multi-platform Support (linux/amd64, linux/arm64)
- GitHub Actions Workflows for CI/CD
- Automated Testing and code quality checks
- Security Vulnerability Scanning
- Automated Dependency Updates
- Docker Image Building and registry push
- Automated Release Management
- Security Headers configuration ready
- CORS Policy management
- Dependency Vulnerability Monitoring
- Secrets Management best practices
- Docker Security with non-root execution
- .NET 9 SDK
- Docker Desktop (optional)
- Git
# Clone the repository
git clone https://github.com/yourorg/dotnet-core-api-template.git
cd dotnet-core-api-template
# Copy environment configuration
cp .env.example .env
# Restore dependencies
dotnet restore# Install EF Tools (if not already installed)
dotnet tool install --global dotnet-ef
# Create and migrate database
./scripts/db-migrate.sh add InitialCreate
./scripts/db-migrate.sh update
# Or on Windows
scripts\db-migrate.bat add InitialCreate
scripts\db-migrate.bat update# Run locally
dotnet run
# Or with hot reload
dotnet watch run
# API will be available at:
# - HTTP: http://localhost:5000
# - HTTPS: https://localhost:5001
# - Swagger: https://localhost:5001/api-docs# Build and run with Docker Compose
docker-compose up --build
# API will be available at:
# - HTTP: http://localhost:8080
# - Swagger: http://localhost:8080/api-docsOnce the application is running, access the interactive API documentation:
- Development: https://localhost:5001/api-docs
- Docker: http://localhost:8080/api-docs
GET /health- Overall application healthGET /health/ready- Readiness probeGET /health/live- Liveness probeGET /api/health/version- Application version info
GET /api/v1/test- Get all sample entities (with pagination)GET /api/v1/test/{id}- Get sample entity by IDPOST /api/v1/test- Create new sample entityPUT /api/v1/test/{id}- Update sample entityDELETE /api/v1/test/{id}- Delete sample entityHEAD /api/v1/test/{id}- Check if sample entity exists
The API supports multiple versioning strategies:
- URL Path:
/api/v1/testor/api/v2/test - Query String:
/api/test?version=1.0or/api/test?v=2.0 - Header:
X-Version: 1.0orX-API-Version: 2.0
βββ src/
β βββ Configuration/ # Application configuration and extensions
β βββ Controllers/ # API controllers
β βββ Data/ # Database context and migrations
β βββ Models/ # Domain models and DTOs
β β βββ DTOs/ # Data Transfer Objects
β βββ Services/ # Business logic services
βββ scripts/ # Build and database scripts
β βββ build.sh # Unix build script
β βββ build.bat # Windows build script
β βββ db-migrate.sh # Unix database migration script
β βββ db-migrate.bat # Windows database migration script
βββ .github/
β βββ workflows/ # GitHub Actions workflows
βββ docs/ # Project documentation
βββ logs/ # Application logs (created at runtime)
βββ Dockerfile # Docker configuration
βββ docker-compose.yml # Development Docker Compose
βββ docker-compose.prod.yml # Production Docker Compose
βββ .env.example # Environment variables template
βββ version.txt # Current version
βββ CHANGELOG.md # Version history
All configuration can be overridden using environment variables. See .env.example for a complete list of available settings.
# Database
ConnectionStrings__DefaultConnection="Server=...;Database=...;"
# API Settings
ApiSettings__Title="Your API Name"
ApiSettings__Version="v1"
# CORS
CorsSettings__AllowedOrigins__0="https://localhost:3000"
CorsSettings__AllowCredentials=true
# Logging
Serilog__MinimumLevel__Default=Informationappsettings.json- Base configurationappsettings.Development.json- Development overridesappsettings.Production.json- Production overrides
The template uses Entity Framework Core with the following features:
- Code-First Migrations
- Automatic Timestamp Management
- Base Entity Classes
- Database Health Checks
- Connection Resilience
# Add new migration
./scripts/db-migrate.sh add MigrationName
# Update database
./scripts/db-migrate.sh update
# View migration status
./scripts/db-migrate.sh status
# Reset database (development only)
./scripts/db-migrate.sh resetThe template includes a comprehensive sample entity demonstrating:
- Primary keys and indexes
- Data annotations and validation
- Different data types (strings, decimals, dates, enums)
- JSON columns for metadata
- Audit fields (CreatedAt, UpdatedAt)
# Build application
./scripts/build.sh build
# Run tests
./scripts/build.sh test
# Create release with version tagging
./scripts/build.sh release -v 1.2.3 -t -p
# Build Docker image
./scripts/build.sh docker-build -v 1.2.3
# Full help
./scripts/build.sh --help# Build application
scripts\build.bat build
# Run tests
scripts\build.bat test
# Create release with version tagging
scripts\build.bat release -v 1.2.3 -t -p
# Build Docker image
scripts\build.bat docker-build -v 1.2.3
# Full help
scripts\build.bat --help# Run with development configuration
docker-compose up --build
# Run with additional services (logging, cache)
docker-compose --profile logging --profile cache up -d# Set environment variables
export TAG=v1.0.0
export DATABASE_CONNECTION_STRING="..."
export FRONTEND_URL="https://yourapp.com"
# Deploy production stack
docker-compose -f docker-compose.prod.yml up -d
# With monitoring
docker-compose -f docker-compose.prod.yml --profile monitoring up -d- Multi-stage builds for optimized size
- Security best practices (non-root user)
- Health checks integration
- Multi-platform support (AMD64, ARM64)
- Proper logging configuration for containers
Triggers on: Push to main/develop, Pull Requests
- β Build and test (Debug & Release)
- β Code quality analysis (SonarCloud)
- β Security vulnerability scanning
- β Package audit for vulnerable dependencies
- β Generate build summaries
Triggers on: Git tags (v*.*.*), Manual dispatch
- π Build and test
- π³ Build multi-platform Docker images
- π¦ Create GitHub releases with artifacts
- π Optional staging deployment
- π Generate deployment summaries
Triggers on: Weekly schedule, Manual dispatch
- π¦ Check for outdated packages
β οΈ Identify vulnerable packages- π« Create GitHub issues for tracking
- π Generate dependency reports
Configure these in your GitHub repository settings:
SONAR_TOKEN # SonarCloud integration
SNYK_TOKEN # Snyk security scanning
CODECOV_TOKEN # Code coverage reporting
DOCKER_REGISTRY_URL # Docker registry (optional)
# Run all tests
dotnet test
# Run with coverage
dotnet test --collect:"XPlat Code Coverage"
# Run specific test category
dotnet test --filter Category=Integrationβββ tests/
β βββ DotNetCoreAPITemplate.UnitTests/ # Unit tests
β βββ DotNetCoreAPITemplate.IntegrationTests/ # Integration tests
β βββ DotNetCoreAPITemplate.EndToEndTests/ # E2E tests
logs/app-*.log- General application logslogs/errors-*.log- Error-only logslogs/http-*.log- HTTP request/response logslogs/performance-*.log- Performance monitoring logslogs/debug-*.log- Debug logs (development only)
- Production: Warning and above
- Staging: Information and above
- Development: Debug and above
// Basic logging
_logger.LogInformation("User {UserId} created entity {EntityId}", userId, entityId);
// Performance logging
using (_logger.BeginScope("Operation: {Operation}", "CreateUser"))
{
// Your code here
}
// Error logging with exception
try
{
// Risky operation
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to process request for user {UserId}", userId);
}- HTTPS Enforcement in production
- CORS Policy configuration
- Security Headers (HSTS, etc.)
- Input Validation with Data Annotations
- SQL Injection Protection via Entity Framework
- Dependency Vulnerability Monitoring
- Docker Security (non-root execution)
- Never commit secrets - Use environment variables
- Regular dependency updates - Automated weekly checks
- Input validation - Validate all API inputs
- Logging security - Don't log sensitive data
- HTTPS only - Enforce in production
- Visual Studio 2022+ or Visual Studio Code
- .NET 9 SDK
- SQL Server LocalDB (Windows) or SQL Server in Docker
- Git
- Create feature branch from
main - Make changes following existing patterns
- Add tests for new functionality
- Run local tests and ensure they pass
- Update documentation if needed
- Create pull request with descriptive title
- CI pipeline will validate your changes
- Follow C# coding conventions
- Use XML documentation for public APIs
- Add comprehensive logging for debugging
- Write unit tests for business logic
- Keep controllers thin - business logic in services
curl -X POST "https://localhost:5001/api/v1/test" \
-H "Content-Type: application/json" \
-d '{
"name": "Sample Item",
"description": "This is a test item",
"isActive": true,
"value": 99.99,
"type": "Premium",
"tags": ["example", "test"],
"metadata": {
"category": "demo",
"priority": 1
}
}'curl "https://localhost:5001/api/v1/test?pageNumber=1&pageSize=10&search=sample&isActive=true"curl "https://localhost:5001/health"- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'feat: add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
We follow Conventional Commits:
feat:New featuresfix:Bug fixesdocs:Documentation updatesstyle:Code style changesrefactor:Code refactoringtest:Test additions or updateschore:Maintenance tasks
See CHANGELOG.md for a detailed history of changes.
This project is licensed under the MIT License - see the LICENSE file for details.
- ASP.NET Core Team for the excellent framework
- Serilog for structured logging
- Swashbuckle for API documentation
- Entity Framework Core for data access
- π Documentation
- π Issue Tracker
- π¬ Discussions
- π§ Email: support@yourcompany.com
Made with β€οΈ by Your Company
This template provides a solid foundation for building production-ready .NET APIs. Feel free to customize it according to your specific requirements and organizational standards.