0

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);
    }
}
3
  • Is this ASP.NET MVC? ASP.NET Web API? Or ASP.NET Core? Please tag your question appropriately to help answerers know what framework you're in and help attract the people knowledgeable about the framework to your question. Commented Sep 10, 2021 at 16:25
  • just do return BadRequest(validationMessages); and return Ok();. Commented Sep 10, 2021 at 16:30
  • Simply use BadRequest() and pass the custom message in that Commented Sep 10, 2021 at 16:32

2 Answers 2

2

Assuming it is ASP.NET Core MVC, the JsonResult class has StatusCode property. So

...
return new JsonResult(ValidationMessages)
{
    StatusCode = StatusCodes.Status400BadRequest
};
...
Sign up to request clarification or add additional context in comments.

Comments

0

You just have to use this the BadRequest() overload described here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.