开发者

WCF Deserialization resets DataMember value to default after OnDeserializing callback

I have developed a WCF Service Application hosted in IIS 7.5 targeting .NET 3.5 configured with only a basicHttpBinding endpoint. The OperationContract signature consists of a Composite type where one of its properties is a custom type. When this property is not initialized by the consuming client, the deserializer on the service appears to ignore the property leaving it null/nothing. I would like to initialize this custom type if it null/nothing and I realize that WCF serialization doesn't call constructors so I've used the deserialization callback. The callback executes and intializes the type but immediately after the callback completes this property returns to null/nothing. Stepping through the code, the ExtensionData property setter executes immediately after the callback and it is at this point where I notice that the property is reset to null/nothing. What am I missing? Here is my sample code

 <DataContract(Name:="Request")> _
Public Class Request
    Im开发者_开发技巧plements IExtensibleDataObject

    <DataMember(Name:="MyCustomType")>
    Public MyCustomType As CustomType 

    Private _ExtensionDataObject As ExtensionDataObject

    Public Overridable Property ExtensionData() As ExtensionDataObject Implements IExtensibleDataObject.ExtensionData
        Get
            Return _ExtensionDataObject
        End Get
        Set(value As ExtensionDataObject)
            _ExtensionDataObject = value
        End Set
    End Property


    <OnDeserializing()>
    Sub OnDeserializing(c As StreamingContext)
        Me.myCustomType = New CustomType()
    End Sub

End Class


If the client didn't initialize the property, then it's value is actually Nothing, and the fact that it is null/Nothing will be present in the serialized Request object. So prior to the deserialization happening, your OnDeserializing method is called, and it initializes the variable; but then the deserialization happens, and since there is a value for the property (which happens to be Nothing/null), it will override it.

I think what you want is to have an OnDeserializ*ed* callback, which will initialize the member after the deserialization happened, if it's value is Nothing:

<OnDeserialized()>
Sub OnDeserialized(ByVal c as StreamingContext)
    If Me.myCustomType Is Nothing Then
        Me.myCustomType = new CustomType()
    End If
End Sub
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜