两种方法MyBehavior :: CreateSerializer()都没有被调用,但是ReplaceBehavior()方法正在运行。它正在使用我的自定义更改默认行为。
有人知道问题出在哪里吗?
重点是编写自定义REST WCF序列化程序,该序列化程序应生成非XML文本格式结果。
public class MySerializerFormatAttribute : Attribute, IOperationBehavior
{
public void AddBindingParameters(OperationDescription description, BindingParameterCollection parameters)
{
}
public void Validate(OperationDescription description)
{
}
private static void ReplaceBehavior(OperationDescription description)
{
DataContractSerializerOperationBehavior dcsOperationBehavior = description.Behaviors.Find<DataContractSerializerOperationBehavior>();
if (dcsOperationBehavior != null)
{
int idx = description.Behaviors.IndexOf(dcsOperationBehavior);
description.Behaviors.Remove(dcsOperationBehavior);
description.Behaviors.Insert(idx, new MyBehavior(description));
}
}
public void ApplyClientBehavior(OperationDescription description, ClientOperation proxy)
{
ReplaceBehavior(description);
}
public void ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch)
{
ReplaceBehavior(description);
}
};
public class MySerializer : XmlObjectSerializer
{
public override bool IsStartObject(XmlDictionaryReader reader)
{
throw new NotImplementedException();
}
public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName)
{
throw new NotImplementedException();
}
public override void WriteEndObject(XmlDictionaryWriter writer)
{
throw new NotImplementedException();
}
public override void WriteObjectContent(XmlDictionaryWriter writer, object graph)
{
throw new NotImplementedException();
}
public override void WriteStartObject(XmlDictionaryWriter writer, object graph)
{
throw new NotImplementedException();
}
}
// Custom Web service behaviour that passes custom serializer
public class MyBehavior : DataContractSerializerOperationBehavior
{
private static MySerializer serializer = new MySerializer();
public MyBehavior(OperationDescription operationDescription) : base(operationDescription)
{
}
public override XmlObjectSerializer CreateSerializer(Type type, string name, string ns, IList<Type> knownTypes)
{
return MyBehavior.serializer;
}
public override XmlObjectSerializer CreateSerializer(Type type, XmlDictionaryString name, XmlDictionaryString ns, IList<Type> knownTypes)
{
return MyBehavior.serializer;
}
}
答案 0 :(得分:6)
在System.ServiceModel.Web世界中完全忽略了这一点。在Reflector中检出DataContractSerializerOperationBehavior。您将看到“System.ServiceModel.Dispatcher.DataContractJsonSerializerOperationBehavior”。如果你对它运行Analyze(Used By),你会看到恐怖:DataContractJsonSerializerOperationFormatter实例化DataContractJsonSerializerOperationBehavior本身。所以...你添加的任何东西都不会做任何事情。
真正糟糕的是操作格式化程序及其周围的所有内容都是内部的。 WCF是非常可扩展的,但构建System.ServiceModel.Web的人似乎讨厌可扩展性。我每周至少遇到一次密封/内部路障。几乎所有的SOAP自定义都不适用于JSON世界。