【问题标题】:Json.Net and validation of Enums in Web APIJson.Net 和 Web API 中的枚举验证
【发布时间】:2019-11-20 11:48:05
【问题描述】:

我正在 .Net Core 2.2 中编写一个 web api。我有一个枚举如下:

使用 System.Runtime.Serialization;

namespace MyNamespace
{
    public enum MyEnum
    {
        [EnumMember(Value = "Some Value")]
        SomeValue
    }
}

如果我在使用枚举的请求中将随机数据作为 MyEnum 传递,我会正确地得到一个错误,但如果我传递“Some Value”或“SomeValue”,它就会通过。如何使“SomeValue”无效? “SomeValue”不在我的大肆宣传中,也不是我想接受的值。

所以基本上,当“SomeValue”不是真正有效时,模型验证通过了。

有什么想法可以让“某些价值”有效吗?谢谢

【问题讨论】:

    标签: c# asp.net-core json.net asp.net-core-2.0 asp.net-core-webapi


    【解决方案1】:

    如果我正确理解了这个问题。您可以使用此示例获取“Some Value”而不是“SomeValue”:

    使用 System.ComponentModel;

     public enum MyEnum
        {
            [Description("Some Value")]
            SomeValue
        }
    

    创建 StringEnumExtension 类:

    public static class StringEnumExtension
        {
            public static string GetDescription<T>(this T e) 
            {
                string str = (string) null;
    
                if ((object) e is Enum)
                {
                    Type type = e.GetType();
                    foreach (int num in Enum.GetValues(type))
                    {
                        if (num == Convert.ToInt32(e, CultureInfo.InvariantCulture))
                        {
                            object[] customAttributes = type.GetMember(type.GetEnumName((object) num))[0]
                                .GetCustomAttributes(typeof(DescriptionAttribute), false);
                            if ((uint) customAttributes.Length > 0U)
                            {
                                str = ((DescriptionAttribute) customAttributes[0]).Description;
                            }
    
                            break;
                        }
                    }
                }
    
                return str;
            }
        }
    

    然后使用下面的代码调用:

     var result = MyEnum.SomeValue.GetDescription();
    

    【讨论】:

    • 嗨,不,我想我把你弄糊涂了。在 Web api 中提交请求时,“SomeValue”和“Some Value”在请求中均有效。
    【解决方案2】:

    过去我在使用 Enums 时遇到过类似的问题,即使使用 EnumMember 属性和默认的 StringEnumConverter 也是如此。

    我最终得到了一个继承自 StringEnumConverter 的自定义转换器,它读取 EnumMember 并将给定的字符串值解析为枚举成员:https://stackoverflow.com/a/58338955/225808

    我已经用额外的空格测试了我的代码,并且在使用我的代码时遇到了验证错误。我匿名了我的代码,这应该对你有用:

    [Required(ErrorMessage = "weather requires a valid value")]
    [JsonProperty("weather")]
    public WeatherEnum? Weather { get; set; }
    

    【讨论】:

    • 嗨,我错过了什么,但 CanConvert 永远不会被调用,
    • 是的。我没有将任何代码与CanConvert 链接。请参考我的链接问题的代码并将其与我在此答案中编写的代码结合起来。
    • 嗨 citronas... 我查看了您的代码,但 CanConvert 从未在我的努力中触发。你确定它是在装饰属性时触发的吗?
    • 请给我看CanConvert的代码。我找不到它
    猜你喜欢
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 1970-01-01
    • 2010-09-06
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多