0

I am working on an asp .net core api project and have some problems on validating input. For validation I use FluentValidation, many will know that lib. Serialization is done by Newtonsoft.Json. The version of the api is 5.0. So coming to my problem: I have a class with a enum property (code snippets will follow). That property is nullable. Null means in my context, there is no value. If there is a value present and I send null in my update route, the value is set to null (and this means, it is not present). My current validator is configured for the property as folowing:

RuleFor(x => x.myEnum).IsInEnum();

This works nearly fine. Null values are accepted, I transfer the string-value or the numeric value for the enumeration, which is defined like that:

public enum MyGreatEnum
{
    [EnumMember(Value = "DAY")]
    Day= 1,
    [EnumMember(Value = "NIGHT")]
    Night=2
}

If I send an empty string ("") to my webapi, it is interpreted as null, which I realy not want. Is there a way to prevent the conversion from "" to null? Or any other possible solution for my struggeling problem?

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
chris000r
  • 297
  • 3
  • 10
  • 1
    But what you want for "" to represent? – Nikita Chayka Dec 10 '20 at 15:11
  • 1
    In the Enum, you could add a new item as the default value, like this `public enum MyGreatEnum {[EnumMember(Value = "Default")]Default = 0, [EnumMember(Value = "DAY")] Day = 1, [EnumMember(Value = "NIGHT")] Night = 2}`. When display the Enum, you could set the default value or using ` – Zhi Lv Dec 11 '20 at 07:44
  • @NikitaChayka in a later step of the request processing, I validate the input object with FluentValidator and would like to throw there a ValidationException. Just to repeat: null means in my context: please remove that value in the database. "" (empty.string) shall not be a valid input in case of enums. – chris000r Dec 15 '20 at 12:37
  • 1
    Then you need to have some Default value in your enum as suggested by @ZhiLv and then you can write your custom converter - https://stackoverflow.com/questions/20104575/how-to-handle-deserialization-of-empty-string-into-enum-in-json-net – Nikita Chayka Dec 15 '20 at 12:42
  • This solution came me also in mind, but I do not like it to be a clean solution. Is there may be another solution? – chris000r Dec 15 '20 at 12:44
  • 1
    No any i am aware of. – Nikita Chayka Dec 15 '20 at 12:47
  • Ok. But really better than no solution, so thanks :-) – chris000r Dec 15 '20 at 12:50

0 Answers0