简体   繁体   中英

Raise json validation error on invalid json using .net core json model binding

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));
}

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 . eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM