ASP.NET MVC How to convert ModelState errors to json

前端 未结 13 2118
余生分开走
余生分开走 2020-12-04 05:24

How do you get a list of all ModelState error messages? I found this code to get all the keys: ( Returning a list of keys with ModelState errors)

var errorK         


        
13条回答
  •  长情又很酷
    2020-12-04 05:45

    The easiest way to do this is to just return a BadRequest with the ModelState itself:

    For example on a PUT:

    [HttpPut]
    public async Task UpdateAsync(Update update)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
    
        // perform the update
    
        return StatusCode(HttpStatusCode.NoContent);
    }
    

    If we use data annotations on e.g. a mobile number, like this, in the Update class:

    public class Update {
        [StringLength(22, MinimumLength = 8)]
        [RegularExpression(@"^\d{8}$|^00\d{6,20}$|^\+\d{6,20}$")]
        public string MobileNumber { get; set; }
    }
    

    This will return the following on an invalid request:

    {
      "Message": "The request is invalid.",
      "ModelState": {
        "update.MobileNumber": [
          "The field MobileNumber must match the regular expression '^\\d{8}$|^00\\d{6,20}$|^\\+\\d{6,20}$'.",
          "The field MobileNumber must be a string with a minimum length of 8 and a maximum length of 22."
        ]
      }
    }
    

提交回复
热议问题