我遇到了在我的WCF应用程序中序列化枚举的问题 .
我有一个类 Account
,它继承自 IAccount
接口,定义如下:
namespace MyNamespace
{
public interface IAccount
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public Country Country { get; set; }
}
}
从 IAccount
继承的 Account
类定义为:
namespace MyNamespace
{
[DataContract]
public Account : IAccount
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string EmailAddress { get; set; }
[DataMember]
public Country Country { get; set; }
}
}
}
国家 Enum
如下:
namespace MyNamespace
{
public enum Country
{
America = 1,
England = 2,
France = 3
}
}
在客户端创建 Account
对象并调用以 OperationContract
装饰的方法AddAccount将Account对象序列化为:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<AddAccount xmlns="http://tempuri.org/">
<account>
<FirstName xmlns="http://schemas.datacontract.org/2004/07/MyNamespace">MyFirstName</FirstName>
<LastName xmlns="http://schemas.datacontract.org/2004/07/MyNamespace">MyLastName</LastName>
<EmailAddress xmlns="http://schemas.datacontract.org/2004/07/MyNamespace">MyEmail@gmail.com</EmailAddress>
</account>
</AddAccount>
</soap:Body>
</soap:Envelope>
您会注意到 Country
枚举没有被序列化 .
我已尝试过使用DataContract和EnumMember修饰枚举,甚至在DataContracts的属性值中显式设置名称空间甚至为EnumMember属性设置值,但似乎没有任何效果 .
我不知道我是疯了还是错过了一些非常明显的东西,或者我还需要做些什么,而这些不是上面代码的一部分 .
UPDATE:
在将WCF应用程序添加为Web引用后,查看在客户端生成的代理类,我注意到枚举不像其他属性那样用 [System.Xml.Serialization.XmlElementAttribute(IsNullable = true)]
进行修饰 .
2 回答
您需要使用以下 Contract 信息来装饰您的枚举:
然后在您的服务 Contract 上添加:
枚举应使用
DataContract
和EnumMember
属性进行修饰 . 您还可以将引用枚举的ServiceKnownType
属性添加到服务 Contract 中 .但总的来说,我建议避免在服务中使用枚举,因为它会导致潜在的向后兼容性问题 . 这是一个问题和一个很好的答案解释这个Do you use enum types in your WCF web services? .