尝试使用DataContractResolver时找不到DataContractSerializerOperationBehavior

时间:2015-12-30 18:52:24

标签: wcf

我正在尝试使用DataContractResolver替代WCF中的KnownTypes。

我有以下代码,我之前在服务器端使用过它。但是在客户端,当尝试在操作行为集合中查找DataContractSerializerOperationBehavior时,代码返回null。

methods

为什么缺少这种行为?

UPDATE :我发现真正的问题是WCF使用的是XmlSerializer而不是DataContractSerializer。有没有办法强制使用DataContractSerializer? WCF是否根据wsdl选择了序列化程序?考虑到我(还)没有能力改变服务器端,我的选择是什么? XmlSerializer行为似乎没有类似的选项来自行解析类型。

1 个答案:

答案 0 :(得分:2)

请参阅此处,了解如何创建DataContractSerializerOperationBehavior(如果它不存在):

private void DataContractBehavior()
{
    WSHttpBinding b = new WSHttpBinding(SecurityMode.Message);
    Uri baseAddress = new Uri("http://localhost:1066/calculator");
    ServiceHost sh = new ServiceHost(typeof(Calculator), baseAddress);
    sh.AddServiceEndpoint(typeof(ICalculator), b, "");

    // Find the ContractDescription of the operation to find.
    ContractDescription cd = sh.Description.Endpoints[0].Contract;
    OperationDescription myOperationDescription = cd.Operations.Find("Add");

    // Find the serializer behavior.
    DataContractSerializerOperationBehavior serializerBehavior =
        myOperationDescription.Behaviors.
           Find<DataContractSerializerOperationBehavior>();

    // If the serializer is not found, create one and add it.
    if (serializerBehavior == null)
    {
        serializerBehavior = new DataContractSerializerOperationBehavior(myOperationDescription);
        myOperationDescription.Behaviors.Add(serializerBehavior);
    }

    // Change the settings of the behavior.
    serializerBehavior.MaxItemsInObjectGraph = 10000;
    serializerBehavior.IgnoreExtensionDataObject = true;

    sh.Open();
    Console.WriteLine("Listening");
    Console.ReadLine();
}

来自https://msdn.microsoft.com/en-us/library/system.servicemodel.description.datacontractserializeroperationbehavior.aspx

的示例