Json.Net和Web API中的枚举验证 [英] Json.Net and validation of Enums in Web API

查看:152
本文介绍了Json.Net和Web API中的枚举验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用.Net Core 2.2编写Web API.我有一个枚举,如下所示:

I'm writing a web api in .Net Core 2.2. I have an enumeration as follows:

使用System.Runtime.Serialization;

using System.Runtime.Serialization;

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

如果我在使用枚举的请求中以MyEnum的形式传递随机数据,我会正确地得到一个错误,但是如果我传递"Some Value"或"SomeValue",它将通过.如何使"SomeValue"无效? "SomeValue"不在我的掌控之中,也不是我想接受的值.

If I pass in random data as MyEnum in a request using the enum I rightly get an error, but if I pass "Some Value" or "SomeValue" it passes. How do I make "SomeValue" invalid? "SomeValue" isn't in my swagger and isn't a value I want to accept.

因此,基本上,当"SomeValue"不是真的有效时,模型验证就会通过.

So basically, model validation passes for "SomeValue" when that isn't really valid.

有什么主意我只能使某些价值"有效吗?谢谢

Any ideas how I can make only "Some Value" valid? Thanks

推荐答案

如果我正确理解了这个问题.您可以使用此示例获取某些价值"而不是某些价值":

If I Understand Correctly the Question.You Can Use This Sample For Get 'Some Value' Instead Of 'SomeValue':

使用System.ComponentModel;

using 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();

这篇关于Json.Net和Web API中的枚举验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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