If I'm creating an API using .NET Core 2.1 with some typical POST and GET methods, which return type for those methods is most suitable, ActionResult<T>
or async Task<T>
? One of my friends uses the latter in every API he creates and that's what was used by the company I was on placement with, whereas the tutorial on PluralSite uses the former. I understand what each one does, but I'm unsure of which should be implemented for any given HTTP request?
The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type.
What is Action Method in ASP.NET Core MVC? Actions are the methods in controller class which are responsible for returning the view or Json data. Action will mainly have return type “ActionResult” and it will be invoked from method InvokeAction called by controller.
However, when you use async Task<ActionResult> and you call in a method within the action that is long running and asynchronous the thread is freed up and a callback is initiated to take over when the long running method returns.
IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance. If a controller action returns an IHttpActionResult, Web API calls the ExecuteAsync method to create an HttpResponseMessage. Then it converts the HttpResponseMessage into an HTTP response message.
ASP.NET Core offers the following options for Web API controller action return types:
Specific type (T)
IActionResult
ActionResult<T>
The Specific
return type is appropriate when you need to return primitive or complex data type without further checking with possibility of different return type (BadRequestResult (400),
NotFoundResult (404), and
OkObjectResult(200)`.) from the action as follows:
[HttpGet]
public async Task<List<Product>> GetProducts()
{
return await _repository.GetProductsAsync();
// Here you can not return Ok(products), NotFound() etc;
// If you need to return NotFound() etc then use `IActionResult` instead of Specific type.
}
The IActionResult
return type is appropriate when multiple ActionResult
return types are possible in an action as follows:
[HttpGet]
public async Task<IActionResult> GetProductById(int id)
{
Product product = await _repository.GetProductByIdAsync(id);
if(product == null)
{
return NotFound(); // Here is one return type
}
return Ok(product); // Here is another return type
}
The ActionResult
types represent various HTTP status codes. Some common return types falling into this category are BadRequestResult (400)
, NotFoundResult (404)
, and OkObjectResult(200)
.
ActionResult<T>
type:ASP.NET Core 2.1 adds new programming conventions that make it easier to build clean and descriptive web APIs. ActionResult<T>
is a new type added to allow an app to return either a response type or any other action result (similar to IActionResult
), while still indicating the response type.
ActionResult<T>
is more specific to Web APIs in ASP.NET Core >= 2.1 and ActionResult<T>
offers the following benefits over the IActionResult
type:
[ProducesResponseType]
attribute's Type property can be excluded.
For example, [ProducesResponseType(200, Type = typeof(Product))]
is
simplified to [ProducesResponseType(200)]
. The action's expected
return type is instead inferred from the T
in ActionResult<T>
.T
and
ActionResult
to ActionResult<T>
. T
converts to ObjectResult
, which
means return new ObjectResult(T);
is simplified to return T;
.For more details: Controller action return types in ASP.NET Core Web API
Third solution: IActionResult Task, something like this:
[HttpGet]
[ProducesResponseType(typeof(IList<Currency>), 200)]
public async Task<IActionResult> GetAll()
{
return Ok(await _typeService.GetCurrenciesAsync().ConfigureAwait(false));
}
[HttpGet("{id}", Name = "GetCurrency")]
[ProducesResponseType(typeof(Currency), 200)]
public async Task<IActionResult> Get([FromRoute]int id)
{
return Ok(await _expenseService.GetCurrencyAsync(id).ConfigureAwait(false));
}
Have a look at an example from Microsoft and why they return the interface instead: IActionResult
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With