ASP.NET Core Web API Structure

Learn the fundamental structure and components of ASP.NET Core Web API for building robust RESTful services

Explore Structure View Examples

What is ASP.NET Core Web API?

ASP.NET Core Web API is a framework for building HTTP services that can be accessed from various clients, including browsers and mobile devices. It is an ideal platform for building RESTful applications on the .NET Core framework.

Program.cs - The Entry Point
var builder = WebApplication.CreateBuilder(args);

// Add services to the container
builder.Services.AddControllers();
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();

Layered Architecture

ASP.NET Core Web API promotes clean separation of concerns with controllers, services, and repositories.

Dependency Injection

Built-in DI container provides loose coupling and easier testing of components.

Middleware Pipeline

Request processing pipeline with customizable middleware components.

Project Structure

Project Root

Contains solution file, startup configuration, and program entry point.

  • Program.cs - Application entry point and middleware configuration
  • Startup.cs (in older versions) - Service configuration
  • appsettings.json - Configuration settings
  • ProjectName.csproj - Project dependencies and settings

Controllers

Handle HTTP requests and return responses. Should be thin and delegate business logic to services.

  • Controller classes inherit from ControllerBase
  • Use attributes for routing and HTTP verbs
  • Return ActionResult or IActionResult types

Models

Represent data structures and business entities used in the application.

  • Data Transfer Objects (DTOs)
  • Entity models for database interaction
  • View models for shaping response data

Services

Contain business logic and application rules. Called by controllers.

  • Interface-based design for testability
  • Registered with dependency injection container
  • Handle complex business operations

Data

Data access layer including database context, repositories, and migrations.

  • DbContext for Entity Framework
  • Repository pattern implementation
  • Database migration files

Dependency Injection Setup

ASP.NET Core has built-in support for Dependency Injection (DI), which makes your application more modular, testable, and maintainable.

Services are registered in Program.cs (or Startup.cs in older versions) and then injected into controllers through constructor injection.

// In Program.cs
builder.Services.AddScoped<IProductService, ProductService>();
builder.Services.AddScoped<IProductRepository, ProductRepository>();

// In Controller
public class ProductsController : ControllerBase
{
    private readonly IProductService _productService;
    
    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }
    
    // Controller actions...
}

API Structure Examples

Controller Structure
// Controllers/ProductsController.cs
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    private readonly IProductService _productService;
    
    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }
    
    // GET: api/products
    [HttpGet]
    public async Task<ActionResult<IEnumerable<ProductDto>>> GetProducts()
    {
        var products = await _productService.GetAllProductsAsync();
        return Ok(products);
    }
    
    // GET: api/products/5
    [HttpGet("{id}")]
    public async Task<ActionResult<ProductDto>> GetProduct(int id)
    {
        var product = await _productService.GetProductByIdAsync(id);
        
        if (product == null)
        {
            return NotFound();
        }
        
        return product;
    }
    
    // Additional actions for POST, PUT, DELETE...
}
Service and Repository Structure
// Services/IProductService.cs and ProductService.cs
public interface IProductService
{
    Task<IEnumerable<ProductDto>> GetAllProductsAsync();
    Task<ProductDto> GetProductByIdAsync(int id);
    Task<ProductDto> CreateProductAsync(CreateProductDto createProductDto);
    // Other method signatures...
}

public class ProductService : IProductService
{
    private readonly IProductRepository _productRepository;
    private readonly IMapper _mapper;
    
    public ProductService(IProductRepository productRepository, IMapper mapper)
    {
        _productRepository = productRepository;
        _mapper = mapper;
    }
    
    public async Task<IEnumerable<ProductDto>> GetAllProductsAsync()
    {
        var products = await _productRepository.GetAllAsync();
        return _mapper.Map<IEnumerable<ProductDto>>(products);
    }
    
    // Other method implementations...
}

Project Structure Comparison

Different approaches to organizing your ASP.NET Core Web API project:

Structure Type Pros Cons Best For
Folder-by-Type Simple to understand, easy for beginners Can become cluttered as project grows Small to medium projects
Feature-Based Better separation of concerns, easier maintenance More complex to set up initially Medium to large projects
Clean Architecture Highly testable, independent of frameworks Steep learning curve, more boilerplate Large, complex enterprise applications
Layered Architecture Clear separation between UI, business logic, and data access Can lead to redundant code Traditional business applications
Feature-Based Folder Structure
ProjectName/
├── Features/
│   ├── Products/
│   │   ├── Models/
│   │   ├── Services/
│   │   ├── Controllers/
│   │   └── Mappings/
│   ├── Orders/
│   │   ├── Models/
│   │   ├── Services/
│   │   ├── Controllers/
│   │   └── Mappings/
│   └── Users/
│       ├── Models/
│       ├── Services/
│       ├── Controllers/
│       └── Mappings/
├── Core/
│   ├── Interfaces/
│   ├── Entities/
│   └── SharedModels/
├── Infrastructure/
│   ├── Data/
│   ├── Repositories/
│   └── Migrations/
└── Program.cs