1

I have some simple controllers that uses .net core model binding for creating an entity using json input.

When sending invalid json (json, that couldn't be parsed correctly because of a typo or missing escape) user will be null and a not usefull error will be thrown.

How could I raise a json validation error and return the information, that json is malformed to the api caller?

[HttpPost]
[ProducesResponseType(typeof(User), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(HttpErrorResponse), StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> Post([FromBody]User user)
{
    return Ok(this.userService.CreateNewUser(user));
}

1 Answer 1

1

There are 2 things that can be done:

First, if it is an API then use the ApiController attribute instead of the Controller attribute. This will handle the model state/parsing error handling for you.

The other option is the check ModelState.IsValid. e.g.

public async Task<IActionResult> Post([FromBody]User user)
{
    if(!this.ModelState.IsValid)
       return BadRequest(this.ModelState);
    return Ok(this.userService.CreateNewUser(user));
}

The first option has my preference. Also because it seems that it produces a better error in case of invalid json.

Sign up to request clarification or add additional context in comments.

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.