简体   繁体   English

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

[英]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" .我想通过返回例如$"{propertyName} input value '77-77-7777' is an invalid date"来自定义这些错误。 For every DateTime property对于每个 DateTime 属性

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

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

相关问题 将 JsonPatchDocument 转换为字符串 C# - Convert JsonPatchDocument to string C# 我正在用C#构建API /框架,当属性设置为无效值时,应该如何返回验证错误消息? - I'm building an API/Framework in C#, how should I return validation error messages when properties are set to an invalid value? 使用“ if”在C#中给出自定义错误消息 - Using “if” to give custom error messages in C# C#.NET:当属性设置为无效值时,是否可以创建编译时警告? - C# .NET: Is it possible to create compile time warnings when property is set to invalid values? 反序列化json时如何避免ModelState中的无效错误 - How to avoid invalid error in ModelState when deserializing a json 使用 C# Fluent Validation,是否可以创建自定义错误消息来说明集合的特定成员失败的原因? - Using C# Fluent Validation, is it possible to create custom error messages which state why specific members of collection fail? ModelState 无效时触发 InvalidModelStateResponseFactory - Triggering InvalidModelStateResponseFactory when ModelState is invalid 如何在 JsonPatchDocument.Applyto 中使用 ModelState - How to use ModelState with JsonPatchDocument.Applyto 自定义异常消息C# - Custom Exception Messages C# 如何从 C# 中的 JsonPatchDocument 对象获取实际值? - How to get actual value from object of JsonPatchDocument in C#?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM