ASP.NET Core Web API Interview Question #45
What does CreatedAtRoute do?
DTOs, Model Binding, Validation & API Responses Junior Beginner
Quick Interview Answer
CreatedAtRoute returns HTTP 201 Created and builds the Location header from a named route rather than directly naming an action method.
Detailed Explanation
CreatedAtRoute returns HTTP 201 Created and builds the Location header from a named route rather than directly naming an action method.
It is useful when route naming is part of the API design or when the location should be generated independently of a particular controller method name.
Code Example
[HttpGet("{id:int}", Name = "GetProduct")]
public IActionResult GetById(int id) => Ok();
[HttpPost]
public IActionResult Create(CreateProductRequest request)
{
return CreatedAtRoute(
"GetProduct",
new { id = 10 },
new { id = 10 });
}