c# - 枚举未在 WCF 中序列化

标签 c# web-services wcf

我在 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; }
   }
}

继承自IAccountAccount类定义为:

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/

相关文章:

java - getResourceAsStream() 总是返回 null

c# - 将 WCF 服务转换为 asmx

c# - 在 WCF 服务中的异步方法调用期间检测连接失败

wcf - 为什么我的客户发送请求如此缓慢?

c# - 你如何运行你的测试?

c# - 如何防止 .NET 库在关闭时发送 RST 数据包

java - Jersey 休息 api 安全

web-services - 如何使用 JAX-WS 生成 WSDL 2.0

c# - BLE 扫描间隔 Windows 10

c# - FluentScheduler 构造函数中的依赖注入(inject)