Explain how to return data in three ways in ASP. NET Core Web API

  • 2021-11-24 01:18:05
  • OfStack

In ASP. NET Core, there are three ways to return data and HTTP status codes, the simplest of which is to return the specified type instance directly, as shown in the following code:

  public class WeatherForecastController : ControllerBase
    public IEnumerable<WeatherForecast> Get()
      var rng = new Random();
      return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]

In addition to this, you can also return IActionResult instances and ActionResult < T > Instance.

Although returning the specified type is the simplest and rudest, it can only return data without http status code, while IActionResult instance can bring data + Http status code 1 to the front end, and finally ActionResult < T > It encapsulates the first two, and can realize the free switching between the two modes,

Related articles: