【问题标题】:Return response in default wrapper在默认包装器中返回响应
【发布时间】:2021-10-21 18:44:55
【问题描述】:

我正在用 ASP.NET 开发一个 Web API。 当我使用时:

return BadRequest( result.Errors );

响应只是一系列错误。为了保持一致性,我希望将错误包装在与其他 asp.net 错误相同的包装器中,如下所示:

{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|803e532a-47325349ba863a12.",
"errors": {
    "Password": [
        "The Password field is required."
    ]
}
}

如何实现这个结果?

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    最简单的方法之一是返回ValidationProblemDetails

    ModelState.AddModelError("Password", "Password field is required");
    return ValidationProblem(ModelState);
    

    或者

    return ValidationProblem(new ValidationProblemDetails(
        new Dictionary<string, string[]>
        {
            {"Password", new[] {"Password field is required."}}
        }));
    

    【讨论】:

      【解决方案2】:

      一般情况下,我们可以使用Validation属性添加验证url,如果模型无效,则返回ModelState(包含指定的key和错误信息):

      public class UserModel
      {
          [Required]
          public string Username { get; set; }
          [Required]
          [StringLength(5)]
          public string EmailAddress { get; set; }
      }
      

      API方法如下:

      [Route("api/[controller]")]
      [ApiController]
      public class ToDoController : ControllerBase
      {
          [HttpPost("AddUser")]
          public IActionResult AddUser([FromBody] UserModel user)
          {
              if (!ModelState.IsValid)
              {
                  return BadRequest(ModelState);
              }
      
              //the the Model is valid, 
              var isvalid = ModelState.IsValid;
      
      
              //Then, if you want to add some exteneral validation, and meet the invalid validation, you can add an if statement
              //if statement.
              // use AddModelError() method to add the new error to the model state.
              ModelState.AddModelError("UserId", "userId id required");
              
              return BadRequest(ModelState);
      
              //else statement return to the next page.
          }
      

      那么,当使用无效数据访问API方法时,结果如下:

      如果我们使用有效数据访问API方法并添加自定义模型错误,结果如下:

      此外,您还可以创建一个包含返回字段的自定义 ValidationError 模型,然后尝试使用操作过滤器来处理 Validation failure 错误响应。更多详细信息,请参考我在线程中的回复:I need to return customized validation result (response) in validation attributes in ASP.Net core Web API

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-09-02
        • 1970-01-01
        • 1970-01-01
        • 2017-08-13
        • 2011-03-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多