2011-08-23 102 views
1

我想確保在我們的WCF中返回數據集的所有操作都具有在Property SchemaSerializationMode中設置的.ExcludedSchema值。在WCF操作中修改返回值

我可以使用CustomBehavior執行此操作嗎? 我試圖實現一個CustomDispatchBehavior並添加一個MessageInspector,但AfterReceiveRequest和BeforeSendReply方法不會讓我對返回值做任何事情。在BeforeSendreply中,返回值已經被序列化。我可以在哪裏插入我的代碼?

public class CustomDispatchBehavior : BehaviorExtensionElement, IServiceBehavior 
    { 

     public override Type BehaviorType 
     { 
      get { return typeof(CustomDispatchBehavior); } 
     } 

     protected override object CreateBehavior() 
     { 
      return new CustomDispatchBehavior(); 
     } 

     void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters) 
     { 
      //throw new NotImplementedException(); 
     } 

     void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
     { 
      //throw new NotImplementedException(); 
      foreach (ChannelDispatcher chanDisp in serviceHostBase.ChannelDispatchers) 
      { 
       foreach (EndpointDispatcher ed in chanDisp.Endpoints) 
       { 
        ed.DispatchRuntime.MessageInspectors.Add(new MyMessageInspector()); 

       } 
      } 
     } 

     void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
     { 
      //throw new NotImplementedException(); 
     } 

    } 

回答

1

我解決它使用IParametorInspector

void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) 
    {  

     foreach (ChannelDispatcher chDisp in serviceHostBase.ChannelDispatchers) 
     { 
      foreach (EndpointDispatcher epDisp in chDisp.Endpoints) 
      {     
       foreach (DispatchOperation op in epDisp.DispatchRuntime.Operations) 
        op.ParameterInspectors.Add(new DataSetParameterInspector()); 
      } 
     } 

    } 

巡查員看起來像這樣

public class DataSetParameterInspector : IParameterInspector 
{ 

    public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState) 
    { 
     Type t =returnValue.GetType(); 
     if (t.IsSubclassOf(typeof(GlobalUtils.RR.Response))) 
     { 
      foreach (var pi in t.GetProperties()) 
      { 
       if (pi.PropertyType.IsSubclassOf(typeof(System.Data.DataSet))) 
       { 
        object parameter = pi.GetValue(returnValue, null); 
        if (parameter != null) 
         ((System.Data.DataSet)parameter).SchemaSerializationMode = System.Data.SchemaSerializationMode.ExcludeSchema; 
       } 
      } 
     } 
    }