无法将 [FromForm] 枚举映射到 asp.net 核心 api 3.1 中的 [EnumMember]

Can't map [FromForm] enum with [EnumMember] in asp.net core api 3.1

我有一个枚举,其值指定为 EnumMemberAttribute:

public enum HireStrategy
{
    [EnumMember(Value = "30-days")]
    Days30,
    [EnumMember(Value = "60-days")]
    Days60,
    [EnumMember(Value = "90-days")]
    Days90
}    

我希望能够使用值 30-days60-days90-days 作为我的 api 的输入参数。 这是服务配置:

services
    .AddControllers()
    .AddNewtonsoftJson(config =>
    {
        config.SerializerSettings.Converters.Add(new StringEnumConverter(typeof(CamelCaseNamingStrategy)));
    });

services
    .AddMvc();            

而我的行动:

[HttpPost("test")]
public async Task<IActionResult> Test(HireStrategy type)
{
    return Ok();
}        

但是,当我尝试使用请求时(通过邮递员) https://localhost:44329/api/v1/users/test?type=60-days 我收到验证错误,即它甚至没有影响我的操作:

{
    "errors": {
        "type": [
            "The value '60-days' is not valid."
        ]
    },
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|b5f15582-4dc901ce029dfb30."
}

当我将“days60”作为值传递时,它工作正常。 有什么我想念的吗? 谢谢!


更新 #1: 我试图禁用 ApiController 验证以查看 newtonsoft 是否处理请求:

services.Configure<ApiBehaviorOptions>(options =>
{
    options.SuppressModelStateInvalidFilter = true;
});            

但是参数被映射到默认值,即 Days30

基于@dbc 在评论中提供的答案。我唯一改变的是使用 CamelCaseNamingStrategy 来确保 pascal 或 camel 大小写被视为有效值。

public class EnumMemberConverter<T> : EnumConverter
{
    private readonly CamelCaseNamingStrategy _camelCaseNamingStrategy;

    public EnumMemberConverter(Type type) 
        : base(type) 
    {
        _camelCaseNamingStrategy = new CamelCaseNamingStrategy();
    }

    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        var type = typeof(T);

        foreach (var field in type.GetFields())
        {
            if (Attribute.GetCustomAttribute(field, typeof(EnumMemberAttribute)) is EnumMemberAttribute attribute
                && value is string enumValue
                && _camelCaseNamingStrategy.GetPropertyName(attribute.Value, false) == _camelCaseNamingStrategy.GetPropertyName(enumValue, false))
            {
                return field.GetValue(null);
            }
        }          

        return base.ConvertFrom(context, culture, value);
    }
}    
[TypeConverter(typeof(EnumMemberConverter<HireStrategy>))]
public enum HireStrategy
{
    [EnumMember(Value = "30-days")]
    Days30,
    [EnumMember(Value = "60-days")]
    Days60,
    [EnumMember(Value = "90-days")]
    Days90
}