Home > OS >  .NET 6 OpenAPI: How to specify required properties in a POST request class?
.NET 6 OpenAPI: How to specify required properties in a POST request class?

Time:06-10

When creating a POST request class, what is the correct way to specify required properties?

Previously I would just use [Required] annotation from System.Data.Annotations. But with .NET 6, nullable reference types have suddenly come into play.

OpenAPI will show the following as an optional property:

public class MyPostRequest
{
    public SomeType? MyOptionalProperty { get; set; }
}

But what is the correct way to specify required properties? The following are the two ways I can think of, but I am unsure which is most "correct":

public class MyPostRequest
{
    #pragma warning disable CS8618
    public SomeType MyRequiredProperty { get; set; }
    #pragma warning restore CS8618
}

public class MyPostRequest
{
    [Required]
    public SomeType? MyRequiredProperty { get; set; }
}

CodePudding user response:

Both solutions are correct but I find the second approach better. Suppressing a warning is not always recommended unless there is no other solution. (Warning made for reasons)

OpenApi will understand the Required annotation anyways and will mark the property as required even if it is nullable. enter image description here

You can however add a property default value or disable the nullable for the whole project to get rid of the nullable ?

public SomeType? SomeProperty {get;set;}

OR

public SomeType SomeProperty {get;set;} = new SomeType();

The default value will initialize the property implicitly but it will not guarantee that this property will not have the null value in the end. (obj.SomeProperty = null;)

As you mentioned, we cannot rely on data input coming from the client. I, personally, am not a big fan of annotation as a sort of validation. I rather use either custom validation or some validation libraries like FluentValidation which will give you complete control over the behavior of the exceptions, and the validation results and will allow complex validation.

  • Related