Hi anonymous user,
if (ModelState.IsValid)
{
StringBuilder value = new StringBuilder();
foreach (ModelStateEntry values in ModelState.Values)
{
value.Append(values);
}
return BadRequest(value.ToString());
}
Model state represents errors that come from two subsystems: model binding and model validation. Errors that originate from model binding are generally data conversion errors. For example, an "x" is entered in an integer field. Model validation occurs after model binding and reports errors where data doesn't conform to business rules. For example, a 0 is entered in a field that expects a rating between 1 and 5.
The ModelState.Values
stores the invalid model property and its Model validation error message.
If the model validation is valid (ModelState.IsValid is true), the ModelState.Values
is empty, if the ModelState.IsValid
is false, the ModelState.Values
contains the invalid property and the error message, check this screenshot:
So, if you want to get ModelState.Values
, try to modify your code as below:
[HttpPost("send")]
public IActionResult Post([FromBody] RequestDto dto)
{
if (ModelState.IsValid)
{
//model id valid.
}
else
{
//model is invalid
StringBuilder value = new StringBuilder();
foreach (ModelStateEntry values in ModelState.Values)
{
value.Append(values);
}
}
return Ok(dto);
}
[Note] In the above sample, it is not an API method. Web API controllers don't have to check ModelState.IsValid if they have the [ApiController]
attribute. In that case, an automatic HTTP 400 response containing error details is returned when model state is invalid. For more information, see Automatic HTTP 400 responses and Model validation in ASP.NET Core MVC and Razor Pages.
return CreateResponse(() => _sendTask.Send(model, false));
Besides, it seems that you want to transfer the model to the CreateResponse method, if that is the case, you can add a parameter in the CreateResponse method to receive the model, like this:
[HttpPost("send")]
public IActionResult Post([FromBody] RequestDto dto)
{
if (ModelState.IsValid)
{
//model id valid.
CreateResponse(dto);
}
else
{
//model is invalid
StringBuilder value = new StringBuilder();
foreach (ModelStateEntry values in ModelState.Values)
{
value.Append(values);
}
}
return Ok(dto);
}
protected void CreateResponse(RequestDto model)
{
var name = model.Name;
}
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion