对于无效值,枚举反序列化为0

时间:2017-12-18 19:35:15

标签: c# json json.net deserialization

我的API初始化如下:

var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
formatter.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
formatter.SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true });

我的枚举看起来类似于以下内容:

public enum EventType
{        
    Value1 = 1,
    Value2 = 5,        
    Value3 = 3,
    Value4 = 4        
}

它使用的类如下:

public class ManualEventModel
{
    public Guid Id { get; set; }

    public EventType EventType { get; set; }

    public DateTime Timestamp { get; set; }

    public bool Active { get; set; }
}

现在,如果我使用EventType=Value5或任何其他非法值调用API,则不会出现错误,但属性EventType的值设置为0.

如何过滤掉非法值?

0 个答案:

没有答案