StringEnumConverter无效的int值 [英] StringEnumConverter invalid int values

查看:241
本文介绍了StringEnumConverter无效的int值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有POST方法的简单Controller.
我的模型具有枚举类型的属性.
当我发送有效值时,一切都会按预期进行

I have a simple Controller with a POST method.
My model has a property of type enum.
When I send valid values ,everything works as expected

{  "MyProperty": "Option2"}

{  "MyProperty": 2}

如果我发送了无效的字符串

If I send an invalid string

{  "MyProperty": "Option15"}

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

it correctly gets the default value (Option1) but if I send an invalid int ,it keep the invalid value

{  "MyProperty": 15}

我可以避免这种情况并获取默认值或抛出错误吗?

Can I avoid that and get the default value or throw an error?

谢谢

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
}

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

Update
I know I can cast any int to an enum,that's not the problem.
@AakashM's suggestion solves half my problem,I didn't know about AllowIntegerValues

现在我在发布无效的int时正确地得到了一个错误

Now I correctly get an error when Posting an invalid int

{  "MyProperty": 15} 

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

The only problematic case now is when I post a string which is a number (which is strange because when I send an invalid non numeric string it correctly fails)

{  "MyProperty": "15"}

推荐答案

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

I solved my problem by extending StringEnumConverter and using @ AakashM's suggestion

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;
    }

}

这篇关于StringEnumConverter无效的int值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆