【发布时间】:2014-03-09 21:22:50
【问题描述】:
在我的 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 属性设置值,但似乎没有任何效果。
我不知道我是不是发疯了,错过了一些非常明显的东西,还是我需要做的其他事情不是上面代码的一部分。
更新:
查看添加 WCF 应用程序作为 Web 引用后在客户端生成的代理类,我注意到枚举没有像其他属性那样用 [System.Xml.Serialization.XmlElementAttribute(IsNullable = true)] 修饰。
【问题讨论】:
-
不要在 WCF 服务中使用枚举类型。
标签: c# web-services wcf