Search code examples
c#fluentvalidation

How to get the same response pattern when doing fluentvalidation manually


When I use fluentvalidation in the normal form I have one response, but when I tried to use it mannually I have another response, how can I get the same response manually?

Normal Response

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-dc7d6c683021ab4e8b3e2db42748e569-ec9d9967213d614c-00",
    "errors": {
        "LicensePlate": [
            "'License Plate' não pode ser nulo."
        ]
    }
}

Manual

public ActionResult<ResponseUpdateLeadVehicleDTO> ChangeLeadPlate1(int id, [CustomizeValidator(Skip = true)]RequestUpdateLeadVehicleDTO request)
{    
  if (!validation.IsValid)
  {
    validation.AddToModelState(ModelState, null);
    return BadRequest(ModelState);
  }
}

response

{
    "LicensePlate": [
        "'License Plate' não pode ser nulo."
    ]
}

Solution

  • Found the answer, right after posted the question. Thanks to Kevin Smith at Adding errors to model state and returning bad request within asp.net core 3.1

    We need to injecting in ApiBehaviorOptions in to our action, these options are used to describe how the api should behavior. One of the options is a factory to create the response back from the api when the model state is invalid, this is called InvalidModelStateResponseFactory. We can call this factory with the ControllerContext which will give us back an IActionResult in which we can return back to the action.

    public IActionResult ChangeLeadPlate1(int id,
      [CustomizeValidator(Skip = true)] RequestUpdateLeadVehicleDTO request,
      [FromServices] IOptions<ApiBehaviorOptions> apiBehaviorOptions)
    {   
      if (!ModelState.IsValid)
        return apiBehaviorOptions.Value.InvalidModelStateResponseFactory(ControllerContext);
    }