关于具有多态数据合同的c#:REST-反序列化失败

 2021-04-27 

REST with Polymorphic DataContracts - Deserialization Fails

这整天让我发疯,因为我没有进行任何更改,但我发誓这按我昨天的意图进行。

我具有通过以下合同定义的WCF 4 REST服务:

1
2
3
4
5
6
7
[ServiceContract]
public interface IPhoneFeaturesManagementHost
{
    [OperationContract]
    [WebInvoke(Method ="POST", UriTemplate ="/accounts/{accountNumber}/phoneNumbers/{phoneNumber}/features/{featureType}", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare)]
    void UpdateFeatureStatus(string accountNumber, string phoneNumber, string featureType, FeatureUpdateRequest updateRequest);
}

我还定义了以下类型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[DataContract]
[KnownType(typeof(One900FeatureUpdateRequest))]
public abstract class FeatureUpdateRequest
{
    [DataMember]
    public FeatureStatus Status { get; set; }

    [DataMember]
    public DateTime EffectiveDate { get; set; }

    public string AccountNumber { get; set; }
    public string PhoneNumber { get; set; }
    public string UserId { get; set; }
    public DateTime Timestamp { get; set; }

    public override string ToString()
    {
        return String.Format("Status: {0}, Effective Date: {1}", Status, EffectiveDate);
    }
}

[DataContract]
public class One900FeatureUpdateRequest : FeatureUpdateRequest
{
    [DataMember]
    public bool PerformSwitchUpdate { get; set; }
}

昨天我发誓我能够提交这种形式的POST数据:

1
2
3
4
5
<One900FeatureUpdateRequest>
  <EffectiveDate>1999-05-31T11:20:00</EffectiveDate>
  <Status>Enabled</Status>
  <PerformSwitchUpdate>true</PerformSwitchUpdate>
</One900FeatureUpdateRequest>

今天,同一批XML导致HTTP 400错误并显示以下消息:

1
Unable to deserialize XML body with root name 'One900FeatureUpdateRequest' and root namespace '' (for operation 'UpdateFeatureStatus' and contract ('IPhoneFeaturesManagementHost',  'http://tempuri.org/')) using DataContractSerializer. Ensure that the type corresponding to the XML is added to the known types collection of the service.

今天看来,唯一可行的XML是以下内容,我真的不喜欢添加名称空间加属性来描述子DataContract子类型的必要性。

1
2
3
4
5
<FeatureUpdateRequest i:type="One900FeatureUpdateRequest" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Project.Services.Host">
  <EffectiveDate>1999-05-31T11:20:00</EffectiveDate>
  <Status>Enabled</Status>
  <PerformSwitchUpdate>true</PerformSwitchUpdate>
</FeatureUpdateRequest>

对于回到以前的简单XML格式进行反序列化的过程,有人对我可能碰到的东西或需要更改的东西有任何想法吗?

任何帮助将不胜感激。谢谢!


我找不到使用DataContractSerializer进行此操作的方法,因此我改用了旧的XmlSerializer,因此可以直接控制XML格式。这似乎可行。