I'm using .NET Core 5 Web API and I am trying to determine is there a better pattern than my current logic for handling 400 bad requests.
It is similar to this question - Best practice to return errors in ASP.NET Web API
Below is my code
[HttpPost("register-customer")]
[Produces("application/json")]
[MapToApiVersion("1")]
public async Task<ActionResult<IRegistrationStatus>> RegisterCustomer([FromBody] Customer customer)
{
try
{
if (customer == null)
return StatusCode(400, "Request body is required");
if (string.IsNullOrEmpty(customer.FirstName))
return StatusCode(400, "First name is required");
if (string.IsNullOrEmpty(customer.LastName))
return StatusCode(400, "Last name is required");
if (string.IsNullOrEmpty(customer.EmailAddress))
return StatusCode(400, "Email address is required");
if (customer.Roles == null || customer.Roles.Count == 0)
return StatusCode(400, "At least one role is required");
//call service to register
return Ok(registrationStatus);
}
catch (Exception ex)
{
return StatusCode(500, ex.ToString());
}
}
All the code works fine but I am wondering is there a better pattern I could use that multiple if statements for each prop I want to check. I also have other APIs for RegisterEmployee for example and the employee class is a different model but it has some of the same fields that are getting checked for 400 - i,e FirstName, LastName - I dont really want to change the Models to sit behind say a Person Interface whcih I guess I could do and then both Employee and Customer would inherit from it - if I did it could be a breaking change for the consumers of my APIs