-1
I have a class that has as attribute an Enum, for example the class below:
public enum Model { Volvo = 1, Ferrari = 2, Gurgel = 3 }
public class Car
{
public Model model { get; private set; }
public Car(Model model)
{
if (Enum.IsDefined(typeof(Model), model))
throw new Exception("Quero que arrebente esta exception");
this.model = model;
}
}
If I pass the right Json to a controller, an instance of the CAR class will be mounted normally, but if I pass the wrong Json, the CAR class object will be null and won’t even enter the constructor. It would not be right to enter the constructor regardless of whether the value is right or wrong?
Json certain
{
"model" : "Volvo"
}
Wrong json
{
"model" : "Arno"
}
Controller method
public async Task<IActionResult> AddCar([FromBody]Car car)
{
if (car == null) //CAI AQUI QUANDO O VALOR DO ENUM NÃO EXISTE.
}
You’re being very critical of who you’re trying to help you with. A from the comment seems that the question is unclear then. If you’ve done something wrong, do you want the person to say it’s right? Then you don’t want help. It is not possible to do the right thing with a wrong problem statement, you can’t say you want to add two things and talk to not consider that there is a sum. I answered over what you wrote, if you wanted to write something else you should have written that other thing.
– Maniero
Boy...you’re being very critical of someone who didn’t understand the question. 1. All that’s up there are examples, that is, don’t take into account whether I’m lifting an Exception or not in a constructor. (I know very well what the constructor is for, so your recommendation is bad) 2. The question of the Enum VALUE being wrong in JSON is precisely the x of the question, since the invalid value does not let me even get to the car EXAMPLE constructor, probably this is at the time of the json deserialization in the controller’s Middle.
– nmapv
the CAR class object will be null and will not enter the constructor. Wouldn’t it be right to enter the constructor regardless of whether the value is right or wrong? This question is very objective and your answer has nothing to do with this question...!
– nmapv