Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.2 kB
2
Indexable
Never
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;

namespace mynewapi.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;
        private List<WeatherForecast> forecasts = new List<WeatherForecast>();

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet(Name = "GetWeatherForecast")]
        public IEnumerable<WeatherForecast> Get()
        {
            return GenerateWeatherForecasts(5);
        }

        // Endpoint for a GET request to retrieve a single forecast by ID
        [HttpGet("{id}", Name = "GetWeatherForecastById")]
        public IActionResult GetById(int id)
        {
            if (id >= 0 && id < forecasts.Count)
            {
                return Ok(forecasts[id]);
            }
            else
            {
                return NotFound();
            }
        }

        // Endpoint for a POST request to add a new weather forecast
        [HttpPost]
        public IActionResult Post([FromBody] WeatherForecast forecast)
        {
            if (forecast == null)
            {
                return BadRequest();
            }

            // Add the new forecast to the list
            forecasts.Add(forecast);

            // Return all the weather forecasts, including the newly added one
            return Ok(forecasts);
        }

        private IEnumerable<WeatherForecast> GenerateWeatherForecasts(int count)
        {
            return Enumerable.Range(1, count).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = new Random().Next(-20, 55),
                Summary = Summaries[new Random().Next(Summaries.Length)]
            }).ToArray();
        }
    }
}