WCF中的自定义对象

时间:2011-09-14 20:15:13

标签: wcf rest c#-4.0

我有以下对象,当我指定标准对象(如int,string)而不是自定义对象时,它可以正常工作。

[DataContract(Namespace = "")]
public class StatusLog<TItem>
{
    /// <summary>
    /// Gets or sets the key.
    /// </summary>
    /// <value>
    /// The key.
    /// </value>
    [DataMember]
    public Guid Id { get; set; }

    /// <summary>
    /// Gets or sets the action status.
    /// </summary>
    /// <value>
    /// The action status.
    /// </value>
    [DataMember]
    public ActionStatus ActionStatus { get; set; }

    /// <summary>
    /// Gets or sets the object.
    /// </summary>
    /// <value>
    /// The object.
    /// </value>
    [DataMember]
    public TItem Object { get; set; }

    /// <summary>
    /// Gets or sets the message.
    /// </summary>
    /// <value>
    /// The message.
    /// </value>
    [DataMember]
    public string Message { get; set; }
}

这有效: 返回新的StatusLog {Id = Guid.NewGuid(),ActionStatus = ActionStatus.Deleted,Object = Convert.ToInt32(id),Message =“Node deleted successfully”};

这不起作用: new StatusLog {Id = Guid.NewGuid(),ActionStatus = ActionStatus.Created,Object = MyCustomObject};

2 个答案:

答案 0 :(得分:3)

查看KnownType属性。

答案 1 :(得分:1)

正如flosk8所提到的,DataContractSerializer在反序列化DataContract时不会知道要考虑哪些类型,除非它使用KnownType属性进行修饰。

http://msdn.microsoft.com/en-us/library/ms730167.aspx

尝试将以下属性添加到DataContract:

[DataContract(Namespace = "")]
[KnownType(typeof(MyCustomObject))]
public class StatusLog<TItem>
{
  // ... snip ...
}

您需要为每个可能需要反序列化到StatusLog.Object属性的类型添加此属性。此外,每种类型都需要可序列化。