【发布时间】:2020-10-15 09:24:26
【问题描述】:
我想创建一个 .NET Core REST API 作为两个系统之间的代理。接收系统接收特定值,但发送系统发送不同变化的值。
鉴于以下示例,接收系统需要以下类型为string 的性别键
- 男性
- 女性
- 多样化
- 未定义
发送系统可能会发送“男性”的变体,例如“米”。如果 DTO 中的值为“m”,我想将其转换为“male”。如果键不存在,它应该简单地返回一个 400。我知道我可以创建验证属性,但我也可以创建转换属性吗?
也许我可以直接转换属性中的DTO值?
这是我当前的示例,展示了我想要实现的目标
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class MyValidationAttribute : System.ComponentModel.DataAnnotations.ValidationAttribute
{
public override bool IsValid(object value)
{
if (value != null)
{
string key = value.ToString();
switch (key)
{
case "male":
case "m":
key = "male"; // Transform the value from the DTO here
break;
case "female":
case "f":
key = "female"; // ...
break;
// ...
default:
return false; // Throw 400 because the value didn't match
}
}
return false;
}
public override string FormatErrorMessage(string name) => "... Invalid ...";
}
【问题讨论】:
标签: c# .net-core asp.net-core-webapi