使用端点行为的WCF自定义序列化

时间:2014-01-14 15:16:42

标签: c# wcf xml-serialization

我有一个在LAN上运行的服务,除了我创建的客户端之外没有客户端。我一直在尝试删除默认的DataContractSerializerOperationBehavior并将其替换为我编写的自定义,并且迄今为止一直非常不成功。我正在使用C#4.5并在NetTcpBindings上运行。

我使用protobuf-net的实现作为示例编写了以下3个类。我只会包括我认为是课程主要部分的内容。如果需要更多细节,我会提供。

CustomXmlObjectSerializer:XmlObjectSerializer

CustomSerializerOperationBehavior:DataContractSerializerOperationBehavior

public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes) {
    return new CustomXmlObjectSerializer();
}

public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes) {
    return new CustomXmlObjectSerializer();
}

CustomEndpointBehavior:IEndpointBehavior

private void ReplaceDataContractSerializerOperationBehavior(ServiceEndpoint endpoint) {
    foreach (var operation in endpoint.Contract.Operations)
        ReplaceDataContractSerializerOperationBehavior(operation);
}

private void ReplaceDataContractSerializerOperationBehavior(OperationDescription operation) {
    for (var i = 0; i < operation.Behaviors.Count; i++) {
        if (operation.Behaviors[i] is DataContractSerializerOperationBehavior) {
            operation.Behaviors[i] = new CustomSerializerOperationBehavior(operation);
            break;
        }
    }
}

服务主机的实例化如下所示:

serviceHost = new ServiceHost(typeof(ImplementationType));
var contract = typeof(ContractType);
var binding = GetBinding(configuration.Address, configuration.MaxTransferSize * 1024 * 1024);
var endpoint = serviceHost.AddServiceEndpoint(contract, binding, configuration.Address);
endpoint.Behaviors.Add(new CustomEndpointBehavior());
serviceHost.Open();

服务客户端的实例化如下所示:

var binding = GetBinding(configuration.Address, configuration.MaxTransferSize * 1024 * 1024);
var endpoint = new EndpointAddress(configuration.Address);
factory = new ChannelFactory<ContractType>(binding, endpoint);
factory.Endpoint.Behaviors.Add(new CustomEndpointBehavior());

当我这样做时,我可以看到CustomEndpointBehavior用我的CustomSerializerOperationBehavior替换DataContractSerializerOperationBehavior但是我实际上从未看到调用创建CustomXmlObjectSerializer(及其后续用法)。

我已经尝试将我的绑定从NetTcpBinding切换到BasicHttpBinding并且没有看到行为发生变化。

有没有人知道为什么,即使在观察每个操作的默认DataContractSerializerOperationBehavior被CustomSerializerOperationBehavior替换后,我实际上没有看到序列化行为的变化?

0 个答案:

没有答案