In the previous exercise, you created a web application that provides sample weather forecast data, then interacted with it in the HTTP Read-Eval-Print Loop (REPL).
Before you dive in to writing your own PizzaController
class, let’s look at the code in the WeatherController
sample to understand how it works. In this unit, you learn how WeatherController
uses the ControllerBase
base class and a few .NET attributes to build a functional web API in a few dozen lines of code. After you understand those concepts, you’re ready to write your own PizzaController
class.
Here’s the code for the entire WeatherController
class. Don’t worry if it doesn’t make sense yet. Let’s go through it step by step.
C#Copy
using Microsoft.AspNetCore.Mvc;
namespace ContosoPizza.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
nodejs training courses malaysia
Leave a Reply