Learn the fundamental structure and components of ASP.NET Core Web API for building robust RESTful services
Explore Structure View ExamplesASP.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.
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();
ASP.NET Core Web API promotes clean separation of concerns with controllers, services, and repositories.
Built-in DI container provides loose coupling and easier testing of components.
Request processing pipeline with customizable middleware components.
Contains solution file, startup configuration, and program entry point.
Handle HTTP requests and return responses. Should be thin and delegate business logic to services.
Represent data structures and business entities used in the application.
Contain business logic and application rules. Called by controllers.
Data access layer including database context, repositories, and migrations.
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...
}
// 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...
}
// 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...
}
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 |
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