I am building a simple minimal api using net6. I am working with enable I have a simple model like this:
public record MyModel(string Prop_1, string Prop_2);
I have an endpoint defined as follows:
builder.MapPut("/models/save",
async (MyModel model) =>
{
// Do something to save the model
});
The issue is that even when the record is defined in a way that MyProp_1 can not be null, if I call this endpoint with the following body, I get an instance of MyModel with null as the value of Prop_1
{ "Prop_2": "Some value" }
In brief: omitting a non-nullable property in the body causes, after the model binding, an instance of the model with the required property having a null value. I was expecting something like a model-binding error. Could anyone explain why is this happening?
The nullable reference type feature in C# is a compiler checked semantic. Even still you can compile and run a program with uninitialized properties, you will just get a compiler warning for it. As always you should check your inputs before using them.
Update
It seems like minimal api does not support model validation at all out of the box. There are some third party solutions however if you want this "for free" you will have to go the old mvc or razor page route.