The following is an example of a web api controller as the current example stands I and wondering what the best practices should be to do the following handle errors of bad data that is passed in and returning notification back to the requester? Looking at best practice are there other noticeable omissions that would be helpful in following best practices?
[Route("api/Animals")]
public class AnimalController : Controller
{
const string DBConnectionString = "data source=(local);integrated security=true";
public AnimalController()
{
}
[HttpPost]
public IActionResult GetAnimalByName([FromBody]string param)
{
var db = new DbConnection(DBConnectionString);
List<Animal> animalList = db.Animal.Where(e => e.AnimalName.Contains(param)).ToList();
return Ok(animalList);
}
[HttpPost]
public IActionResult PostNewAnimal([FromBody]Animal newAnimal)
{
if (newAnimal == null || newAnimal.AnimalName == null)
{
return BadRequest("New animal model must be supplied");
}
var db = new DbConnection(DBConnectionString);
bool duplicateFound = db.Animal.Where(e => e.AnimalName == newAnimal.AnimalName).Any();
if(duplicateFound)
{
return BadRequest("Animal name already exist");
}
else
{
db.Animal.Add(newAnimal);
}
return Ok();
}
}