Overview
Controllers are the core of ASP.NET Web API. They handle HTTP requests, execute business logic, and return responses. Controllers are simple classes that inherit from ControllerBase
and are decorated with routing attributes.
Creating a Controller
Use the ApiController
attribute and inherit from ControllerBase
:
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
// GET api/products
[HttpGet]
public IEnumerable<Product> Get()
{
// ...
}
}
Action Methods
Typical HTTP verbs are mapped with attributes:
[HttpGet]
– Retrieve resources[HttpPost]
– Create a new resource[HttpPut]
– Update a resource[HttpDelete]
– Delete a resource
// GET api/products/5
[HttpGet("{id}")]
public ActionResult<Product> Get(int id)
{
var product = _service.Find(id);
if (product == null) return NotFound();
return Ok(product);
}
// POST api/products
[HttpPost]
public ActionResult<Product> Post([FromBody] ProductDto dto)
{
var created = _service.Create(dto);
return CreatedAtAction(nameof(Get), new { id = created.Id }, created);
}
Routing
Routes can be defined at the controller or action level using attribute routing:
[Route("api/v{version:apiVersion}/[controller]")]
public class OrdersController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult Get(int id) { … }
}
Model Binding & Validation
Parameters are automatically bound from the request body, route, query string, or headers.
public class CreateUserDto
{
[Required]
public string UserName { get; set; }
[EmailAddress]
public string Email { get; set; }
}
[HttpPost]
public IActionResult Create([FromBody] CreateUserDto dto)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
// …
return Created(...);
}
Complete Example
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class CustomersController : ControllerBase
{
private readonly ICustomerService _service;
public CustomersController(ICustomerService service) => _service = service;
// GET api/customers
[HttpGet]
public async Task> GetAll()
{
var customers = await _service.GetAllAsync();
return Ok(customers);
}
// GET api/customers/5
[HttpGet("{id}")]
public async Task Get(int id)
{
var customer = await _service.GetByIdAsync(id);
if (customer == null) return NotFound();
return Ok(customer);
}
// POST api/customers
[HttpPost]
public async Task Create([FromBody] CreateCustomerDto dto)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
var created = await _service.CreateAsync(dto);
return CreatedAtAction(nameof(Get), new { id = created.Id }, created);
}
// PUT api/customers/5
[HttpPut("{id}")]
public async Task Update(int id, [FromBody] UpdateCustomerDto dto)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
var success = await _service.UpdateAsync(id, dto);
if (!success) return NotFound();
return NoContent();
}
// DELETE api/customers/5
[HttpDelete("{id}")]
public async Task Delete(int id)
{
var removed = await _service.DeleteAsync(id);
if (!removed) return NotFound();
return NoContent();
}
}