|
| 1 | +using Microsoft.AspNetCore.Mvc; |
| 2 | +using System.ComponentModel.DataAnnotations; |
| 3 | + |
| 4 | +namespace SystemTextJsonPatch.ApiTest.Controllers |
| 5 | +{ |
| 6 | + [Route("api/[controller]")] |
| 7 | + public class WeatherController : ControllerBase |
| 8 | + { |
| 9 | + private readonly WeatherForecast[] _weatherForecasts = new WeatherForecast[] |
| 10 | + { |
| 11 | + new WeatherForecast { Date = DateTime.Now, TemperatureC = 25, Summary = "Hot" }, |
| 12 | + new WeatherForecast { Date = DateTime.Now.AddDays(1), TemperatureC = 20, Summary = "Warm" }, |
| 13 | + new WeatherForecast { Date = DateTime.Now.AddDays(2), TemperatureC = 15, Summary = "Cool" }, |
| 14 | + new WeatherForecast { Date = DateTime.Now.AddDays(3), TemperatureC = 10, Summary = "Cold" }, |
| 15 | + new WeatherForecast { Date = DateTime.Now.AddDays(4), TemperatureC = 5, Summary = "Freezing" } |
| 16 | + }; |
| 17 | + |
| 18 | + [HttpGet] |
| 19 | + public IActionResult GetWeather() |
| 20 | + { |
| 21 | + return Ok(_weatherForecasts); |
| 22 | + } |
| 23 | + |
| 24 | + [HttpPost] |
| 25 | + public ActionResult<WeatherForecast> PostWeather([FromBody, Required] WeatherForecast? weatherForecast) |
| 26 | + { |
| 27 | + if (weatherForecast == null || ModelState.IsValid == false) |
| 28 | + { |
| 29 | + return ValidationProblem(this.ModelState); |
| 30 | + } |
| 31 | + |
| 32 | + return CreatedAtAction(nameof(GetWeather), weatherForecast); |
| 33 | + } |
| 34 | + |
| 35 | + [HttpPatch("{id}")] |
| 36 | + public IActionResult PatchWeather(int id, [FromBody, Required] JsonPatchDocument<WeatherForecast>? patchDoc) |
| 37 | + { |
| 38 | + var weatherForecast = _weatherForecasts[id]; |
| 39 | + if (weatherForecast == null) |
| 40 | + { |
| 41 | + return NotFound(); |
| 42 | + } |
| 43 | + |
| 44 | + patchDoc.ApplyTo(weatherForecast); |
| 45 | + TryValidateModel(weatherForecast); |
| 46 | + if (ModelState.IsValid == false) |
| 47 | + { |
| 48 | + return ValidationProblem(this.ModelState); |
| 49 | + } |
| 50 | + |
| 51 | + return Ok(); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + public class WeatherForecast |
| 56 | + { |
| 57 | + public DateTime Date { get; set; } |
| 58 | + [Required] |
| 59 | + public int? TemperatureC { get; set; } |
| 60 | + public string Summary { get; set; } |
| 61 | + } |
| 62 | +} |
0 commit comments