详解如何在ASP.NET Core Web API中以三种方式返回数据
在ASP.NETCore中有三种返回数据和HTTP状态码的方式,最简单的就是直接返回指定的类型实例,如下代码所示:
[ApiController]
[Route("[controller]")]
publicclassWeatherForecastController:ControllerBase
{
[HttpGet]
publicIEnumerableGet()
{
varrng=newRandom();
returnEnumerable.Range(1,5).Select(index=>newWeatherForecast
{
Date=DateTime.Now.AddDays(index),
TemperatureC=rng.Next(-20,55),
Summary=Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
}
除了这种,也可以返回IActionResult实例和ActionResult
虽然返回指定的类型是最简单粗暴的,但它只能返回数据,附带不了http状态码,而IActionResult实例可以将数据+Http状态码一同带给前端,最后就是ActionResult