我在 WCF 应用程序中序列化枚举时遇到问题。
我有一个 Account
类,它继承自 IAccount
接口(interface),定义如下:
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; }
}
}
国家枚举
如下:
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 属性设置值,但似乎没有任何效果。
我不知道我是不是疯了,错过了一些非常明显的东西,还是我需要做的其他事情不是上面代码的一部分。
更新:
查看在将 WCF 应用程序添加为 Web 引用后在客户端生成的代理类,我注意到枚举未使用 [System.Xml.Serialization.XmlElementAttribute(IsNullable = true)] 修饰
与其他属性一样。
最佳答案
您需要使用一些契约(Contract)信息来装饰您的枚举,例如:
[DataContract]
public enum Country
{
[EnumMember]
America = 1,
[EnumMember]
England = 2,
[EnumMember]
France = 3
}
然后在您的服务契约(Contract)上添加:
[ServiceContract]
[ServiceKnownType(typeof(Country))]
public interface IMyService {
// etc..
}
关于c# - 枚举未在 WCF 中序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22288339/