简体   繁体   English

使用 .net 核心 json 模型绑定在无效 json 上引发 json 验证错误

[英]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.我有一些简单的控制器,它们使用 .net 核心模型绑定来使用 json 输入创建实体。

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.当发送无效的 json(json,由于拼写错误或缺少转义而无法正确解析)时,用户将为 null,并且将抛出无用的错误。

How could I raise a json validation error and return the information, that json is malformed to the api caller?我如何引发 json 验证错误并返回信息,即 json 对 api 调用者格式不正确?

[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.首先,如果它是一个 API,那么使用ApiController属性而不是Controller属性。 This will handle the model state/parsing error handling for you.这将为您处理模型状态/解析错误处理。

The other option is the check ModelState.IsValid .另一个选项是检查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.也因为它似乎在无效 json 的情况下会产生更好的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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