Hello, I would like you to help me. I have made a web api that only returns a message, and it has input parameters that I have in an Entities class, I will detail below:
1.Controller
[HttpPost]
public string Visualizar([FromBody] Usuarios usuarios)
{
try
{
var result = _contexto.visualizar(usuarios);
return result;
}
catch(exception ex)
{
return ex.message.tostring()
}
}
2. User class of the entities layer has the following:
public int idusuario {get;set;}
public string nombre {get;set;}
public int edad {get;set;}
It works correctly when I have tried it, but as now in my work there is a QA area that is in charge of validating the services, the test by the postman but the one where int
it is placed data of string
something like this by the postman
{
"idusuario":"Hola Mundo",
"nombre":"pepe",
"edad" : "no se"
}
and when executing the postman, the following message is displayed, and it is correct because the format is incorrect, but he wants a string to appear in my response that I return and he tells me that my catch must control that
{
"idusuario":[
"the input was not valid."
],
"edad":[
"the input was not valid."
]
}
and he tells me if I try that he should vote for me in your try catch in your message but I can't control that since he doesn't even call my controller to control it, any suggestion that can help me control it?
since you want the string you sent to be controlled by something like this:
{
"mensaje" : "El formato es incorrecto"
}
Well after 2 days, here is the solution is the following create 3 classes which are the following. 1.ValidationError
2.ValidateModelAttribute
3.ValidationFailedResult
In the controller at the beginning place this: [ValidateModel]
and in the startup.
It would be everything.
For .Net core you can do a custom Bindinng:
Defining the user class specifies a custom Binding.
The definition of the Binding:
As you can see the validation errors are simply added to the validation of the model, for Surname and name do not add validation so the value is simply passed.
Once your rules are defined, all you have to do is add it to the configuration, first the provider is defined:
and this is added to the start in the configuration, in the Startup class the provider is added:
In the controller, the invalid fields are returned, if any,
Doing a test with age as string we get:
It can even be used to mark the wrong field in the Greetings Record view.