为什么 WCF 将空字符串反序列化为有效枚举

Why does WCF deserialize empty strings as valid enumerations

比方说我有一个这样写的 C# 数据协定

[DataContract]
public class GiftCard
{
    [DataMember(IsRequired = true, EmitDefaultValue = false)]
    public PaymentMethod MethodOfPayment;
}

[DataContract]
[Flags]
public enum PaymentMethod
{
    [EnumMember]
    Mastercard = 0,
    [EnumMember]
    Visa = 1
}

然后使用 SOAPUI 测试它,故意不指定值。

<soapenv:Body>
  <GiftCardTest>
     <GiftCard>
        <MethodOfPayment></MethodOfPayment>
     </GiftCard>
  </GiftCardTest>
</soapenv:Body>

它到达我的服务方法是有效的

我缺少什么属性?我该如何验证?

当反序列化值时,如果在反序列化期间找不到要使用的有效值,则必须设置默认值。所以它使用 default(PaymentMethod)(PaymentMethod)default(int) 相同。

default(int) 的值为 0,您必须使 0 成为无效的枚举值或使 MethodOfPayment 可为空,这样默认值将为 null 而不是 0。

删除 Flags 属性就成功了。

[DataContract]
public enum PaymentMethod
{
    [EnumMember]
    Mastercard = 0,
    [EnumMember]
    Visa = 1
}

它现在抛出异常:

Invalid enum value '' cannot be deserialized into type 'PaymentMethod'...