繁体   English   中英

C# JsonPatchDocument:当ModelState无效时是否可以设置自定义错误消息

[英]C# JsonPatchDocument: Is it possible to set custom error messages when ModelState is invalid

例如,当输入了无效日期时,响应消息将如下所示。

{
     "errors": {
         "AccountDto": [
             "The value '77-77-7777' is invalid for target location."
          ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400
}

我想通过返回例如$"{propertyName} input value '77-77-7777' is an invalid date"来自定义这些错误。 对于每个 DateTime 属性

将此方法添加到您的控制器:

public async Task<IActionResult> Patch([FromBody] JsonPatchDocument<AccountDto> patchDoc)
{
     if (patchDoc is null) 
         return BadRequest("patchDoc is null.");

    // This is an example, you most likely have
    // a service to get the account model
    var account = new Account();
    
    patchDoc.ApplyTo(account, ModelState);
    
    TryValidateModel(account);

    if (!ModelState.IsValid) 
        return UnprocessableEntity(ModelState);
    
    //Save changes...
    
    return NoContent();
}

暂无
暂无

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

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