I have a REST API and I when there is validation message, I want to return an HTTP status of 400 along with the list of validation messages. For example, in Postman I want the status in the tool to show a 400 and in response body show the JSON list of messages.
Is there a way to do this in C#?
public async Task<IActionResult> OnPostAsync([FromBody] ServiceRequest serviceRequest)
{
try
{
var user = User.FindFirst("client_id")?.Value;
int VendorId = await _audit.Log(user, AuditLogClass.API_READ, "serviceData");
List<string> ValidationMessages = _serviceRequestBO.processServiceRequest(serviceRequest);
if (ValidationMessages.Count == 0)
{
await _emailService.SendEmailAsync("[email protected]", "Success", "Service Request created");
return StatusCode(StatusCodes.Status200OK);
}
else
{
//StatusCodes.Status400BadRequest
return new JsonResult(ValidationMessages);
}
}
catch(Exception e)
{
_logger.LogError(e, "serviceData - GET");
return StatusCode(StatusCodes.Status500InternalServerError);
}
}
return BadRequest(validationMessages);andreturn Ok();.