Is DataAnnotation compatible with Json?

-1

Hello! I would like to know if DataAnnotation is compatible with Json, since I am validating a form and would like to remove the doubt. I am using Angular on the front and returning my object in Json format, I would like to validate the return of this json (the information that the user typed in the fields) using DataAnnotation

This is my method of adding:

[HttpPost]
public async Task<string> Add([FromBody]Sindicate objSindicate)
{
    return JsonConvert.SerializeObject(await _service.Add(objSindicate));
}

This is my class using DataAnnotation.

public class SindicateValidator
{
    [Key]

    public Guid SindicateId { get; set; }

    [Required(ErrorMessage = "Nome obrigatório!")]
    [MaxLength(128, ErrorMessage = "Máximo {0} caracteres")]
    [MinLength(2, ErrorMessage = "Minímo {0} caracteres")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Razão Social é obrigatório!")]
    [MaxLength(128, ErrorMessage = "Máximo {0} caracteres")]
    [MinLength(2, ErrorMessage = "Minímo {0} caracteres")]
    public string SocialReason { get; set; }

    [Required(ErrorMessage = "CNPJ é obrigatório!")]
    [DisplayFormat(DataFormatString = "{0:n2}", 
                    ApplyFormatInEditMode = true)]
    [MaxLength(14, ErrorMessage = "Máximo {0} caracteres")]
    public string CNPJ { get; set; }

    [Required(ErrorMessage = "Login é obrigatório!")]
    [MaxLength(128,ErrorMessage = "Máximo {0} caracteres")]
    public string Login { get; set; }

    [Required(ErrorMessage = "Senha é obrigatório!")]
    [MaxLength(8, ErrorMessage = "Máximo {0} caracteres")]
    public string Password { get; set; }

    [Required(ErrorMessage = "E-Mail é obrigatório!")]
    [MaxLength(128, ErrorMessage = "Máximo {0} caracteres")]
    [EmailAddress(ErrorMessage = "Preencha um E-mail válido!")]
    public string Email { get; set; }

    [ScaffoldColumn(false)]
    public DateTime DateCreated { get; set; }

    [ScaffoldColumn(false)]
    public bool Disable { get; set; }

    [ScaffoldColumn(false)]
    public DateTime? DateDisable { get; set; }

    [ScaffoldColumn(false)]
    public bool Deleted { get; set; }

    [ScaffoldColumn(false)]
    public DateTime? DateDeleted { get; set; }
}
    
asked by anonymous 28.03.2018 / 23:37

1 answer

0
The Controller will validate the input independent of the Content-Type used, however it is important that the input is with the notations.

Another point, API by default will serialize the return to JSON , so there is no need to serializar the object previously.

[HttpPost]
public async Task<IHttpActionResult> Add([FromBody]SindicateValidator objSindicate)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);
    var response = await _service.Add(objSindicate);
    return Ok(response);
}
    
29.03.2018 / 15:48