2017-07-21 72 views
0

我有一個WCF服務在我的界面看起來是這樣的:實施IOperationBehavior作爲屬性

[ServiceContract] 
public interface IMyService 
{ 
    [OperationContract] 
    [AllowedFileExtension] 
    void SaveFile(string fileName); 
} 

我的目標是檢查傳入消息來驗證文件名。所以我AllowedFileExtensionAttribute類看起來是這樣的:

public class AllowedFileExtensionsAttribute : Attribute, IOperationBehavior 
{ 
     private readonly string _callingMethodName; 
     private readonly string[] _allowedFileExtension; 

     public AllowedFileExtensionsAttribute([CallerMemberName]string callingMethodName = null) 
     { 
      _callingMethodName = callingMethodName; 
     } 

     public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters) 
     { 

     } 

     public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) 
     { 

     } 

     public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) 
     { 

     } 

     public void Validate(OperationDescription operationDescription) 
     { 

     } 
} 

從例如WCF測試客戶端或一個簡單的控制檯應用程序調用此,則不會調用我的屬性類,它直接進入implmentation。我在這裏做錯了什麼?

+1

我所做的是在'ApplyDispatchBehavior'中,我向'dispatchOperation.ParameterInspectors'添加了一個'IParameterInspector',並在'AfterCall'和'BeforeCall'中實現了攔截。 – Silvermind

回答

2

您可以使用WCF MessageInspector來攔截請求並執行任何您想要的操作。

甲消息檢查是可以在服務模型的客戶端運行時和運行時調度編程方式或通過配置中使用一個擴展的對象,並且可以檢查和它們被接收後改變消息或它們被髮送之前。

您可以實現IDispatchMessageInspectorIClientMessageInspector接口。讀取AfterReceiveRequest中的輸入數據,將其存儲在線程靜態變量中,如果需要,請在BeforeSendRequest中使用它。

AfterReceiveRequest由管道接收到消息時由調度程序調用。您可以操作已作爲參考參數傳遞的此請求。

請參閱msdn doc

public class SimpleEndpointBehavior : IEndpointBehavior 
{ 
    public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) 
    { 
    } 

    public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime) 
    { 
     clientRuntime.MessageInspectors.Add(
      new SimpleMessageInspector() 
      ); 
    } 

    public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher) 
    { 
    } 
    public void Validate(ServiceEndpoint endpoint) 
    { 
    } 
} 



public class SimpleMessageInspector : IClientMessageInspector, IDispatchMessageInspector  
{ 
     public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)  
     { 
     }  

     public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)  
     {  

      //modify the request send from client(only customize message body) 

      request = TransformMessage2(request); 

      //you can modify the entire message via following function 

      //request = TransformMessage(request);  

      return null;  
     } 

} 

查看this post瞭解詳情。