ASP.NET Core Web API Interview Question #7
Why is attribute routing commonly used for Web APIs?
Web API & REST Fundamentals, Controllers, HTTP Methods & Status Codes Junior Beginner
Quick Interview Answer
Attribute routing places route templates directly on controllers and actions. It makes the HTTP contract explicit and works well for APIs because each endpoint can clearly declare its URI pattern, HTTP method, and route constraints.
Detailed Explanation
Attribute routing places route templates directly on controllers and actions. It makes the HTTP contract explicit and works well for APIs because each endpoint can clearly declare its URI pattern, HTTP method, and route constraints.
The ApiController convention expects attribute routing. Clear route definitions also make an API easier to document and reason about.
Code Example
[ApiController]
[Route("api/products")]
public class ProductsController : ControllerBase
{
[HttpGet("{id:int}")]
public IActionResult GetById(int id) => Ok(id);
}