复合类型的整数值在 WCF 操作中变为 null

Integers values of composite type become null at WCF operation

我对 WCF 服务和 c# 有一个奇怪的行为;我正在尝试将复杂类型 [FooRequest] 发送到服务操作; [FooRequest] 有一些属性,其中之一是用户定义类型 [MyType],它只有字符串和整数等简单属性。

现在,当客户端传递包含 y 的 [FooRequest] 对象时,服务器会接收到它,其中包含除 [MyType] 中的整数和小数以外的完整参数。你能帮我吗。

服务合同:

[DataContract]
public enum MessageType
{
    [EnumMember]
    REQ1,
    [EnumMember]
    REQ2        
}

[MessageContract]
public class MyType 
{        
    [MessageHeader]
    public string Title { get; set; }

    [MessageHeader]
    public decimal DecValue { get; set; }

    [MessageHeader]
    public int IntValue { get; set; }
}

[MessageContract]
public class FooRequest
{        
    [MessageHeader]
    public int FooId { get; set; }

    [MessageHeader]
    public MessageType SomeEnum { get; set; }

    [MessageHeader]
    public List<MyType> SomeObject { get; set; }
}

在客户端:

        Svc.FooServiceClient client = new Svc.FooServiceClient();
        FooRequest req = new Svc.FooRequest()
        {
            FooId = 1,
            SomeEnum = MessageType.REQ1,
            SomeObject = (new List<MyType>() { new Svc.MyType() { Title = "txt txt", DecValue = 23.5, IntValue = 500 }}).ToArray()
        };
        FooResponse res = client.MyOperation(req );

在服务器端

public class FooService : IFooService
{
    public FooResponse MyOperation(FooRequest request)
    {
       /*
        request.FooId = 1
        request.SomeEnum  = REQ1
        request.SomeObject.Length = 1
        request.SomeObject[0].Title = "txt txt"
        request.SomeObject[0].DecValue = null ????!!!! here is the problem
        request.SomeObject[0].IntValue = null ????!!!! here is the problem
       */
    }
}

你错误地装饰了你的类型。而不是

[MessageContract]
public class FooRequest
{        
    [MessageHeader]
    public int FooId { get; set; }

应该是

[DataContract]
public class FooRequest
{        
    [DataMember]
    public int FooId { get; set; }

对 MyType 执行相同的操作。所以你只需要改变属性。

如果有人遇到同样的问题,我找到了解决这个问题的方法。使用 [ServiceContract] 向服务接口添加 [XmlSerializerFormat] 装饰将解决问题。我认为这是序列化的某种冲突问题。