[英]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.