3

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

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
user2883072
  • 217
  • 3
  • 12

2 Answers2

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();
Amin Golmahalleh
  • 3,585
  • 2
  • 23
  • 36
  • Hi, no I think I've confused you. When submitting a request in a web api both "SomeValue" and "Some Value" are valid in the request. – user2883072 Nov 20 '19 at 13:02
0

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; }
citronas
  • 19,035
  • 27
  • 96
  • 164