2014-01-23 67 views
0

我目前正在使用消息攔截器,並希望將數據從我的服務方法傳遞給攔截器(即BeforeSendRequest和BeforeSendReply)。但是,我無法弄清楚如何做到這一點。在發送請求和/或回覆之前將數據傳遞給攔截器

我到目前爲止所做的是我有服務執行期間設置的靜態變量,然後在攔截器執行時獲取。這項工作很好,除非多個消息同時發送,其中一個將覆蓋其他值!

回答

1

最簡單的例子是使用消息屬性:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.ServiceModel.Channels; 
using System.ServiceModel.Description; 
using System.ServiceModel.Dispatcher; 
using System.Text; 
using System.Threading.Tasks; 
using System.ServiceModel; 

namespace SO21299236 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var address = new Uri("net.pipe://localhost/" + Guid.NewGuid()); 
      var service = new ServiceHost(typeof (MyService)); 
      var binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None); 
      var ep = service.AddServiceEndpoint(typeof(IMyService), binding, address); 
      ep.Behaviors.Add(new MyBehavior()); 
      service.Open(); 

      var factory = new ChannelFactory<IMyService>(binding, new EndpointAddress(address)); 
      var proxy = factory.CreateChannel(); 
      proxy.DoSomething(); 

      Console.WriteLine("Done."); 
     } 
    } 

    internal class MyBehavior : IEndpointBehavior 
    { 
     public void Validate(ServiceEndpoint endpoint) 
     { 
     } 

     public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters) 
     { 
     } 

     public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher) 
     { 
      endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomMessageInspector()); 
     } 

     public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime) 
     { 
     } 
    } 

    internal class CustomMessageInspector : IDispatchMessageInspector 
    { 
     public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) 
     { 
      return null; 
     } 

     public void BeforeSendReply(ref Message reply, object correlationState) 
     { 
      var prop = reply.Properties.FirstOrDefault(z => z.Key == "MyProperty"); 
      Console.WriteLine(prop.Value); 
     } 
    } 

    [ServiceContract] 
    interface IMyService 
    { 
     [OperationContract] 
     void DoSomething(); 
    } 

    class MyService : IMyService 
    { 
     public void DoSomething() 
     { 
      OperationContext.Current.OutgoingMessageProperties.Add("MyProperty", 1); 
     } 
    } 
} 
+0

'OperationContext.Current.OutgoingMessageProperties'工作好了!謝謝。 – user3186786

相關問題