Misha Zaslavsky
Misha Zaslavsky

Reputation: 9676

Ignore nulls in EnumDataType data annotation attribute

I have a model with a nullable enum and an API layer. In the API layer, I get the model and checking its state. When I send a null value in this enum I get an error message from the model state because the enum cannot be null. Is it possible to change the attribute so that it will ignore and not add error message in case of null?

This is my code:

public class MyModel
{
    [EnumDataType(typeof(MyEnum?))]
    public MyEnum? MyEnum { get; set; }
}

And this the API layer:

[HttpPost]
[Route("")]
public async Task<int> Post(MyModel myModel)
{
    Validate(myModel);

    if (!ModelState.IsValid)
    {
        //Stop the process and return a message...
    }

    //Continue with the process.
    //Call the BL, etc.
}

Upvotes: 1

Views: 1195

Answers (1)

CodeFuller
CodeFuller

Reputation: 31312

First of all you should change the type passed to EnumDataType attribute from MyEnum? to MyEnum. EnumDataType expects enum type but MyEnum? is actually Nullable<MyEnum> which will cause InvalidOperationException.

Then following JSON posted in request body should be correctly deserialized to the model:

{
  "MyEnum": null
}

After deserialization by JSON.NET, MyModel.MyEnum property will be set to null. EnumDataType will not perform any validation for null value and you get valid model.

When I send a null value in this enum I get an error message from the model state because the enum cannot be null.

The most probable reason is that you send null value as a string:

{
  "MyEnum": "null"
}

Such JSON will cause deserialization error (inside JSON.NET), because deserializer does not know how to convert string "null" to MyEnum. This is not an error produced by validation attribute, because any validation is executed only if deserilization completes successfully. Check this answer for more details about model deserialization and validation stages.

Upvotes: 3

Related Questions