简体   繁体   中英

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

When for example an invalid date has been entered the response message will be the following.

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

I want to customize these errors by returning for example $"{propertyName} input value '77-77-7777' is an invalid date" . For every DateTime property

Add this method to your controller:

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

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