gpt4 book ai didi

c# - 无法在 asp.net core api 3.1 中将 [FromForm] 枚举与 [EnumMember] 映射

转载 作者:行者123 更新时间:2023-12-03 08:18:27 29 4
gpt4 key购买 nike

我有一个枚举,并为其值指定了 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();
}

但是,当我尝试使用请求时(通过 postman )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

最佳答案

基于答案here这是@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
}

关于c# - 无法在 asp.net core api 3.1 中将 [FromForm] 枚举与 [EnumMember] 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68624324/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com