问题
While I do understand the concept of Task
, ActionResult
, etc. I still feel unsure which would be most intuitive to type in a controller if nothing else is specified.
Taking consideration to be as explicit with a type returned, I should go like this:
[HttpGet] public ActionResult<Thing> Get()
{
return Ok(Context.Things);
}
However, going for a generic type of API paradigm I should use this:
[HttpGet] public IActionResult Get()
{
return Ok(Context.Things);
}
Finally, respecting the asynchronous nature of the API philosophy I should apply the following:
[HttpGet] public Task<IActionResult> Get()
{
return Ok(Context.Things);
}
I can't decide between which is most appropriate in a general, green-field scenario. The first two work seemingly. Intuitively, I'd prefer to go with the third one but since it didn't work (the conversion isn't valid), I got worried that perhaps I'm barking up the wrong binary tree.
Not sure at all how to google it and I'm obtaining all kinds of examples. Uncertain how to judge which ones are of relevance, I prefer to ask.
回答1:
Here is a quick comparison of the different return options:
Specific type
public Thing Get() {
return Ok(Context.Things);
}
This is OK if the action will always return one possible type. However, most actions may return exceptions (i.e. status codes other than 200) that have different types.
IActionResult type
This solves the problem above as the IActionResult
return type covers different return types.
public IActionResult Get() {
Thing thing = Context.Things;
if (thing == null)
return NotFound();
else
return Ok(thing);
}
For asynchronous action, use Task<IActionResult>
:
public async Task<IActionResult> Get() {
Thing thing = await Context.Things;
if (thing == null)
return NotFound();
else
return Ok(thing);
}
ActionResult type
ASP.NET Core 2.1 introduced the ActionResult<T>
return type which offers the following benefits over the IActionResult
type:
1- The action's expected return type is inferred from the T
in ActionResult<T>
. If you decorate your action with the [ProducesResponseType]
attribute, you no longer need to explicitly specify its Type
property. For example, you can simply use [ProducesResponseType(200)]
instead of [ProducesResponseType(200, Type = typeof(Thing))]
.
2- T
converts to ObjectResult
, which means return new ObjectResult(T);
is simplified to return T;
.
public ActionResult<Thing> Get() {
Thing thing = Context.Things;
if (thing == null)
return NotFound();
else
return thing;
}
For asynchronous action, use Task<ActionResult<T>>
:
public async Task<ActionResult<Thing>> Get() {
Thing thing = await Context.Things;
if (thing == null)
return NotFound();
else
return thing;
}
For more details, you can refer to the MSDN page Controller action return types in ASP.NET Core Web API.
来源:https://stackoverflow.com/questions/54336578/cant-decide-between-taskiactionresult-iactionresult-and-actionresultthing