Skip to content

yaochangyu/api.template

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

213 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

api.template β€” .NET WebAPI Development Template

Language: English | 繁體中文

A comprehensive .NET WebAPI development template implementing Clean Architecture, layered architecture, and Result Pattern best practices.

πŸ“‹ Quick Start

Prerequisites

  • .NET 8+ SDK
  • Docker & Docker Compose (for database and cache test environments)
  • Git

Basic Steps

  1. Clone the project

    git clone https://github.com/yaochangyu/api.template.git
    cd api.template/dotnet-project-template
  2. Configure environment variables

    cp env/local.env .env
    # Edit .env to set local database connection strings, Redis address, etc.
  3. Start development environment

    docker-compose up -d      # Start SQL Server, Redis, etc.
    dotnet build               # Build the solution
    dotnet run --project src/be/JobBank1111.Job.WebAPI
  4. Verify API is running

    curl http://localhost:5000/api/health
  5. Run tests

    dotnet test                # Execute all unit and integration tests

πŸ“ Directory Structure

api.template/
β”œβ”€β”€ .claude/                          # Development tools & AI assistant guides
β”‚   β”œβ”€β”€ CLAUDE.md                     # AI assistant behavior rules & plan management
β”‚   β”œβ”€β”€ development-rules.md          # Development rules & best practices
β”‚   β”œβ”€β”€ decision-framework.md         # Decision logic for API development
β”‚   β”œβ”€β”€ skills/                       # Development helper skill definitions (16 total)
β”‚   β”‚   β”œβ”€β”€ api-development/          # API endpoint design & decision logic
β”‚   β”‚   β”œβ”€β”€ handler/                  # Business logic layer implementation
β”‚   β”‚   β”œβ”€β”€ repository-design/        # Data access layer design
β”‚   β”‚   β”œβ”€β”€ error-handling/           # Unified error handling patterns
β”‚   β”‚   β”œβ”€β”€ middleware/               # HTTP middleware implementation
β”‚   β”‚   β”œβ”€β”€ ef-core/                  # EF Core optimization guide
β”‚   β”‚   β”œβ”€β”€ bdd-testing/              # BDD integration tests (Reqnroll/Gherkin)
β”‚   β”‚   └── [9 other skills]
β”‚   └── agents/                       # AI Agent workflows (architecture review, feature development, etc.)
β”‚
β”œβ”€β”€ dotnet-project-template/          # Main .NET project
β”‚   β”œβ”€β”€ src/be/                       # Backend code
β”‚   β”‚   β”œβ”€β”€ JobBank1111.Infrastructure/    # Shared infrastructure (caching, logging, TraceContext)
β”‚   β”‚   β”œβ”€β”€ JobBank1111.Job.Contract/      # API contracts & auto-generated Client
β”‚   β”‚   β”œβ”€β”€ JobBank1111.Job.DB/            # EF Core DbContext & Entities
β”‚   β”‚   β”œβ”€β”€ JobBank1111.Job.WebAPI/        # API Controllers & middleware
β”‚   β”‚   β”œβ”€β”€ JobBank1111.Job.Test/          # Unit tests (Xunit)
β”‚   β”‚   └── JobBank1111.Job.IntegrationTest/ # Integration tests (Reqnroll/BDD)
β”‚   β”‚
β”‚   β”œβ”€β”€ doc/                          # API specification documents
β”‚   β”‚   └── openapi.yml               # OpenAPI specification (Swagger)
β”‚   β”‚
β”‚   β”œβ”€β”€ env/                          # Environment configuration
β”‚   β”‚   β”œβ”€β”€ .template-config.json     # Template configuration
β”‚   β”‚   └── local.env                 # Local environment variables
β”‚   β”‚
β”‚   β”œβ”€β”€ k8s/                          # Kubernetes deployment configuration
β”‚   β”œβ”€β”€ docker-compose.yml            # Local development environment (DB, Redis)
β”‚   └── Taskfile.yml                  # Common tasks (build, test, deploy)
β”‚
β”œβ”€β”€ CLAUDE.md                         # AI assistant behavior rules & plan management
β”œβ”€β”€ tree.md                           # Complete file listing
└── .archive/                         # Completed plan documents (for reference)

πŸ—οΈ Core Architecture

Layered Design

HTTP Request
     ↓
[ Middleware Layer ]      # Logging, authentication, TraceContext, error handling
     ↓
[ Controller Layer ]      # HTTP routing & request validation (MemberController.cs)
     ↓
[ Handler Layer ]         # Business logic (MemberHandler.cs)
     ↓
[ Repository Layer ]      # Data access abstraction (IMemberRepository)
     ↓
[ EF Core DbContext ]     # ORM implementation
     ↓
[ Database ]              # SQL Server / PostgreSQL

Core Concepts

1. API Development Approach

Choose the appropriate development approach based on your project stage (must choose one, do not mix):

Approach When to Use Example File
API First API specification is finalized, auto-generate Controller MemberV1ControllerImpl.cs
Code First Implement Controller directly without spec auto-generation MemberController.cs

πŸ‘‰ Detailed decision logic: see .claude/decision-framework.md

2. Result Pattern (Unified Result Type)

All API endpoints return a unified Result<T> structure:

{
  "isSuccess": true,
  "data": { ... },
  "failure": null,
  "traceId": "550e8400-e29b-41d4-a716-446655440000"
}
  • Benefits: Unified error handling, complete trace context, automatic logging
  • Implementation: see /error-handling SKILL

3. TraceContext (Request Tracing)

Every request automatically gets a unique TraceId that flows through the entire call chain:

public class TraceContext
{
    public string TraceId { get; set; }  // Globally unique identifier
    public string UserId { get; set; }   // Current user
    public DateTime RequestTime { get; set; }
}

Facilitates log aggregation, performance analysis, and fault diagnosis.

4. Immutable Objects

Use C# record types and init properties to ensure objects cannot be modified after creation:

public record MemberResponse(
    int Id,
    string Name,
    string Email
);

5. Async I/O

All database and network operations use async/await:

public async Task<Result<MemberResponse>> GetMemberAsync(int id)
{
    var member = await _repository.GetByIdAsync(id);
    return member != null 
        ? Result.Ok(new MemberResponse(member.Id, member.Name, member.Email))
        : Result.Fail<MemberResponse>("Member not found");
}

πŸ› οΈ Development Workflow

Typical API Endpoint Implementation Flow

Suppose you need to implement a "Get Member List" endpoint:

  1. Choose development approach (API First or Code First)

    /api-development
  2. Design data access layer

    /repository-design
  3. Implement business logic layer

    /handler
  4. Implement Controller

    /handler   # Also generates Controller reference
  5. Implement BDD tests

    /bdd-testing
  6. Verify completeness

    dotnet test
    dotnet build

πŸ“– Advanced Guides

Consult corresponding documentation based on your task:

Task Related Document Location
Understanding development workflow SKILL usage guide CLAUDE.md
Designing API endpoints API development decision framework .claude/decision-framework.md
Implementing Controller Development rules & best practices .claude/development-rules.md
Writing integration tests BDD testing guide .claude/skills/bdd-testing/SKILL.md
Caching design Caching strategy decision .claude/decision-framework.md#caching-strategy
Security checks Security scanning tools .claude/skills/security-*

πŸ“š Important Documents

πŸ”§ Common Commands

# Development
dotnet build                                    # Build the entire solution
dotnet run --project src/be/JobBank1111.Job.WebAPI   # Start API server
dotnet watch run --project src/be/JobBank1111.Job.WebAPI  # Hot reload mode

# Testing
dotnet test                                     # Execute all tests (unit + integration)
dotnet test --filter FullyQualifiedName~Member # Run specific test

# Database migrations (using EF Core)
dotnet ef migrations add CreateMemberTable --project src/be/JobBank1111.Job.DB
dotnet ef database update --project src/be/JobBank1111.Job.DB

# Docker
docker-compose up -d                            # Start local development environment
docker-compose down                             # Stop development environment
docker-compose logs -f                          # View container logs

🎯 Development Policy

Must Follow

  • βœ… Layered Architecture: Controller β†’ Handler β†’ Repository β†’ DbContext
  • βœ… Immutable Objects: Use records and init properties
  • βœ… Async Operations: All I/O uses async/await
  • βœ… Result Pattern: Unified success/failure type
  • βœ… TraceContext: Every request carries a TraceId
  • βœ… BDD Tests: Integration tests use Gherkin/Reqnroll

Prohibited

  • ❌ Mixing API First and Code First approaches
  • ❌ Skipping async/await (synchronous I/O blocks threads)
  • ❌ Writing business logic directly in Controllers (violates layering)
  • ❌ Mocking databases in integration tests (use real Docker containers)

πŸ—οΈ Architecture Decision

Swagger packages removed in favor of .NET 10 native OpenAPI (commit 15bcdf5)

  • Removed: Swashbuckle.AspNetCore, Swashbuckle.AspNetCore.ReDoc, Scalar.AspNetCore
  • Now using: Microsoft.AspNetCore.OpenApi (built-in .NET 10 support)
  • Program.cs updated: app.MapOpenApi() for native OpenAPI endpoint
  • Simpler, fewer dependencies, native framework integration

πŸ“ž Questions & Support


Version: api.template v1.0
Last Updated: 2026-07-11
Purpose: For both human and AI Agent reading

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Used by

Contributors

Languages