Json.Net and validation of Enums in Web API

旧时模样 提交于 2020-01-10 05:40:09

问题


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

using System.Runtime.Serialization;

namespace MyNamespace
{
    public enum MyEnum
    {
        [EnumMember(Value = "Some Value")]
        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.

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

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


回答1:


I've had similar problems with Enums in the past, even with the EnumMember attribute and the default StringEnumConverter.

I ended up with a custom converter that inherits from StringEnumConverter which reads EnumMember and parses the given string value to the enum member: https://stackoverflow.com/a/58338955/225808

I've tested my code with additional spaces and I get validate errors when using my code. I anonymized my code and this should work for you:

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



回答2:


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

using System.ComponentModel;

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

Create StringEnumExtension Class :

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

Then Use the Code Below to Call :

 var result = MyEnum.SomeValue.GetDescription();


来源:https://stackoverflow.com/questions/58953657/json-net-and-validation-of-enums-in-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!