- ASP.NET Core offers the following three options for Web API controller action return types: Specific Type,
IActionResult
, and ActionResult<T>
.
Specific Type
- It returns a primitive or complex data type.
- Without known conditions to safeguard against during action execution, returning a specific type could suffice.
- The preceding action accepts no parameters, so parameter constraints validation isn't needed.
- When known conditions need to be accounted for in an action, multiple return paths are introduced.
- In such a case, it's common to mix an
ActionResult
return type with the primitive or complex return type.
- Either
IActionResult
or ActionResult<T>
are necessary to accommodate this type of action.
[HttpGet]
public IEnumerable<Product> Get() => _repository.GetProducts()
IActionResult
Type
- The
IActionResult
return type is appropriate when multiple ActionResult
return types are possible in an action.
- The
ActionResult
types represent various HTTP status codes.
- Because there are multiple return types and paths in the action, liberal use of the
ProducesResponseType
attribute is necessary.
- This attribute produces more descriptive response details for API help pages generated by tools like Swagger.
- It indicates the known types and HTTP status codes to be returned by the action.
Synchronous Action
[HttpGet("{id}")]
[ProducesResponseType(200, Type = typeof(Product))]
[ProducesResponseType(404)]
public IActionResult GetById(int id)
{
if (!_repository.TryGetProduct(id, out var product))
return NotFound();
return Ok(product);
}
Asynchronous Action
- The preceding action's other known return code is a 201, which is generated by the
CreatedAtRoute
helper method.
[HttpPost]
[ProducesResponseType(201, Type = typeof(Product))]
[ProducesResponseType(400)]
public async Task<IActionResult> CreateAsync([FromBody] Product product)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
await _repository.AddProductAsync(product);
return CreatedAtAction(nameof(GetById), new { id = product.Id }, product);
}
ActionResult<T>
Type
- The
ActionResult<T>
enables you to return a type deriving from ActionResult
or return a specific type.