JSON Customized for Dataannotations - Asp.Net Core Web Api

Asked

Viewed 152 times

0

Good afternoon!

I have a Web API in . Net Core, where I have the following request class for a POST route:

public class CreateAgentRequest
{
    [Required]
    public Agent Agent { get; set; }
}

With Annotation Required, if I don’t send a field Agent, it returns me the error in the following API call structure

inserir a descrição da imagem aqui

However, I have a customized validation model, which are validations that I do not deal with Data Annotations, for example, that this data already exists in the database.

inserir a descrição da imagem aqui

I have the need to customize this return of Data Annotation (first image), to follow the same pattern as the second image. Is there any way to customize the return of Data Annotation validation?

  • required is a Validationattribute. One option would be to implement your custom attribute, for example Representanteunicoattribute, and use it in the validation pipeline. Example: https://docs.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2

1 answer

0

Good afternoon

You can customize an error message using Dataannotation.Errormessage

public class CreateAgentRequest
{
    [Required(ErrorMessage="Mensagem de Erro")]
    public Agent Agent { get; set; }
}

Now if you want to return the same object of the second image tries to give a check in Dataannotation.Customvalidation, I know that with it you can customize a Validation, and I imagine that the return of it too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.