![](/img/trans.png)
[英]ASP.net Core API returning ActionResult<T> not enforcing return type
[英]ASP.NET Core API - ActionResult<T> vs async Task<T>
如果我使用 .NET Core 2.1 和一些典型的 POST 和 GET 方法创建 API,这些方法的返回类型最合适, ActionResult<T>
或async Task<T>
? 我的一个朋友在他创建的每个 API 中都使用后者,这就是我所在的公司所使用的,而 PluralSite 上的教程使用的是前者。 我了解每个人的作用,但我不确定应该为任何给定的 HTTP 请求实现哪个?
ASP.NET Core 为 Web API 控制器操作返回类型提供以下选项:
Specific type (T)
IActionResult
ActionResult<T>
当您需要返回原始或复杂数据类型而无需进一步检查不同返回类型(BadRequestResult (400) ,
NotFoundResult (404) , and
OkObjectResult(200)`.)的可能性时, Specific
返回类型是合适的,如下所示:
[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.
}
当一个动作中可能有多个ActionResult
返回类型时, IActionResult
返回类型是合适的,如下所示:
[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
}
ActionResult
类型表示各种 HTTP 状态代码。 属于这一类的一些常见返回类型是BadRequestResult (400)
、 NotFoundResult (404)
和OkObjectResult(200)
。
ActionResult<T>
类型: ASP.NET Core 2.1添加了新的编程约定,可以更轻松地构建干净且描述性的 Web API。 ActionResult<T>
是一种新类型,允许应用返回响应类型或任何其他操作结果(类似于IActionResult
),同时仍指示响应类型。
ActionResult<T>
更特定于ASP.NET Core >= 2.1 中的Web API,而ActionResult<T>
比IActionResult
类型具有以下优点:
[ProducesResponseType]
属性的 Type 属性。 例如, [ProducesResponseType(200, Type = typeof(Product))]
简化为[ProducesResponseType(200)]
。 操作的预期返回类型是从ActionResult<T>
的T
推断出来的。T
和ActionResult
到ActionResult<T>
。 T
转换为ObjectResult
,这意味着 return new ObjectResult(T);
简化为return T;
.有关更多详细信息: ASP.NET Core Web API 中的控制器操作返回类型
第三种解决方案:IActionResult 任务,类似这样:
[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));
}
看看微软的一个例子,以及他们为什么返回接口: IActionResult
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.