Can someone review this implemented solution and provide commentary the code is working well but will need refactor and improve this code.
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
namespace PersonUpdateApi.Controllers
{
public class PersonUpdateModel
{
public int Id { get; set; }
public string NewFirstname { get; set; }
public string NewSurname { get; set; }
}
[ApiController]
[Route("[controller]")]
public class PersonController : ControllerBase
{
private readonly IConfiguration _config;
private Logger _logger;
public PersonController(IConfiguration config)
{
_config = config;
}
public void LogUpdateRequest(PersonUpdateModel p)
{
_logger.Info($"Update request received. Person ID: {p.Id}, New forename = {p.NewFirstname}, New surname = {p.NewSurname}");
}
private void LogSuccessfulUpdate(PersonUpdateModel p)
{
_logger.Info($"Update request was successful for Person ID: {p.Id}.");
}
private void LogException(PersonUpdateModel p, Exception ex)
{
_logger.Info($"An error occurred when updating the person. Person ID: {p.Id}, New forename = {p.NewFirstname}, New surname = {p.NewSurname}", ex);
}
[HttpPost]
public IActionResult Update(PersonUpdateModel p)
{
_logger = new Logger();
LogUpdateRequest(p);
if (string.IsNullOrWhiteSpace(p.NewFirstname))
return BadRequest("There was no firstname specified");
if (string.IsNullOrWhiteSpace(p.NewSurname))
return BadRequest("There was no surname specified");
if (p.Id < 1)
return BadRequest("Invalid person ID");
string dbConnectionStr = _config.GetValue<string>("Database:ConnectionString");
int dbTimeoutInSeconds = 120;
try
{
string updateSql = "UPDATE People SET Firstname = '" + p.NewFirstname + "', Surname = '" + p.NewSurname + "' WHERE PersonId = " + p.Id;
Database db = new Database();
db.ExecuteNonReturningQuery(dbConnectionStr, updateSql, dbTimeoutInSeconds);
}
catch(Exception ex)
{
LogException(p, ex);
return BadRequest("There was an error updating the person in the database. Please try again later.");
}
LogSuccessfulUpdate(p);
return Ok("The update was successful");
}
}
}