Custom DataContractSerializerOperationBehavior

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; 
     
} 
   
} 

posted @ 2011-01-20 16:53  牟向阳  阅读(608)  评论(1编辑  收藏  举报