Skip to content

Instantly share code, notes, and snippets.

@JsAndDotNet
Created May 3, 2022 12:49
Show Gist options
  • Save JsAndDotNet/0c4654965ae52cb99a6877207958a1b4 to your computer and use it in GitHub Desktop.
Save JsAndDotNet/0c4654965ae52cb99a6877207958a1b4 to your computer and use it in GitHub Desktop.
Example API Problem Return
using Microsoft.AspNetCore.Mvc;
namespace TestForAPIM.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 async Task<ActionResult<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();
}
[ProducesResponseType(400)]
[ProducesResponseType(typeof(WeatherForecast), 200)]
[HttpPost(Name = "PostWeatherForecast")]
public async Task<ActionResult<WeatherForecast>> Post([FromBody]WeatherForecast weatherForecast)
{
if(weatherForecast.Date < DateTime.Now)
{
return Problem(
title: "Forecast dates must be in the future",
statusCode: 400,
instance: HttpContext.Request.Path
);
}
// Should save here in practice
if(weatherForecast.TemperatureC > 30)
{
weatherForecast.Summary = "Feelin' hot hot hot!!!";
}
return weatherForecast;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment