StringEnumConverter无效的int值

Geo*_*vos 3 c# json.net asp.net-web-api

我有一个带有POST方法的简单Controller。
我的模型具有枚举类型的属性。
当我发送有效值时,一切正常

{  "MyProperty": "Option2"}
Run Code Online (Sandbox Code Playgroud)

要么

{  "MyProperty": 2}
Run Code Online (Sandbox Code Playgroud)

如果我发送无效的字符串

{  "MyProperty": "Option15"}
Run Code Online (Sandbox Code Playgroud)

它正确获取默认值(Option1),但是如果我发送无效的int,它将保留无效值

{  "MyProperty": 15}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

我可以避免这种情况并获得默认值还是抛出错误?

谢谢

public class ValuesController : ApiController
{
    [HttpPost]
    public void Post(MyModel value) {}
}

public class MyModel
{
    [JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
    public MyEnum MyProperty { get; set; }
}

public enum MyEnum
{
    Option1 = 0,
    Option2,
    Option3
}
Run Code Online (Sandbox Code Playgroud)

更新
我知道我可以将任何int强制转换为枚举,这不是问题。
@AakashM的建议解决了我一半的问题,我不知道AllowIntegerValues

现在我在发布无效的int时正确地收到错误

{  "MyProperty": 15} 
Run Code Online (Sandbox Code Playgroud)

现在唯一有问题的情况是当我发布一个数字字符串时(这很奇怪,因为当我发送无效的非数字字符串时,它正确地失败了)

{  "MyProperty": "15"}
Run Code Online (Sandbox Code Playgroud)

Geo*_*vos 5

我通过扩展StringEnumConverter并使用@ AakashM的建议解决了我的问题

public class OnlyStringEnumConverter : StringEnumConverter
{
    public OnlyStringEnumConverter()
    {
        AllowIntegerValues = false;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (!AllowIntegerValues && reader.TokenType == JsonToken.String)
        {
            string s = reader.Value.ToString().Trim();
            if (!String.IsNullOrEmpty(s))
            {
                if (char.IsDigit(s[0]) || s[0] == '-' || s[0] == '+')
                {
                    string message = String.Format(CultureInfo.InvariantCulture, "Value '{0}' is not allowed for enum '{1}'.", s, objectType.FullName);
                    string formattedMessage = FormatMessage(reader as IJsonLineInfo, reader.Path, message);
                    throw new JsonSerializationException(formattedMessage);
                }
            }
        }
        return base.ReadJson(reader, objectType, existingValue, serializer);
    }

    // Copy of internal method in NewtonSoft.Json.JsonPosition, to get the same formatting as a standard JsonSerializationException
    private static string FormatMessage(IJsonLineInfo lineInfo, string path, string message)
    {
        if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
        {
            message = message.Trim();
            if (!message.EndsWith("."))
            {
                message += ".";
            }
            message += " ";
        }
        message += String.Format(CultureInfo.InvariantCulture, "Path '{0}'", path);
        if (lineInfo != null && lineInfo.HasLineInfo())
        {
            message += String.Format(CultureInfo.InvariantCulture, ", line {0}, position {1}", lineInfo.LineNumber, lineInfo.LinePosition);
        }
        message += ".";
        return message;
    }

}
Run Code Online (Sandbox Code Playgroud)