在ASP.NET Core Web API中,使用ActionResult
要解决此问题,我们可以使用Microsoft.AspNetCore.Mvc.Api.Analyzers NuGet包中的ProducesResponseType属性来指定返回值类型和状态代码,而不是使用ActionResult
[HttpGet("{id}")]
[ProducesResponseType(typeof(Item), 200)]
public IActionResult Get(int id)
{
var item = _repository.FindById(id);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
在这个示例中,使用ProducesResponseType属性来指定返回类型为Item,并且状态代码为200。这个方法现在可以在Swagger UI中正常工作。
通过使用ProducesResponseType属性,我们可以避免在Swagger UI上使用ActionResult