wcf 消息拦截
说明:命名空间为:WcfServiceInterpector
1:新建继承自IDispatchMessageInspector的ServiceInterpector类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class ServiceInterpector : IDispatchMessageInspector
2 {
3
4 #region IDispatchMessageInspector 成员
5
6 public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
7 {
8 ICSS.Plover.Log.LogRecorder.WriteInfo(new LogMessage("请求服务地址:" + request.Headers.To.AbsoluteUri + " 调用方法地址:" + request.Headers.Action));
9 return "success";
10 }
11
12 public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
13 {
14
15 }
16
17 #endregion
18 }
2:新建继承自BehaviorExtensionElement, IServiceBehavior的MyServiceBehavior类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class MyServiceBehavior : BehaviorExtensionElement, IServiceBehavior
2 {
3
4 public override Type BehaviorType
5 {
6 get { return typeof(MyServiceBehavior); }
7 }
8 protected override object CreateBehavior()
9 {
10 return new MyServiceBehavior();
11 }
12 #region IServiceBehavior Members
13 public void AddBindingParameters(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
14 {
15 }
16 public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
17 {
18 foreach (ChannelDispatcher chDisp in serviceHostBase.ChannelDispatchers)
19 {
20 foreach (EndpointDispatcher epDisp in chDisp.Endpoints)
21 {
22 epDisp.DispatchRuntime.MessageInspectors.Add(new ServiceInterpector());
23 }
24 }
25 }
26 public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
27 {
28 }
29 #endregion
30
31 }
3:配置文件中添加配置
(1)添加扩展
<system.serviceModel>
<extensions>
<behaviorExtensions>
<add name="Test" type="WcfServiceInterpector.MyServiceBehavior, WcfServiceInterpector, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</behaviorExtensions>
</extensions>
</system.serviceModel>
说明:type="类完整名称, (程序集名称), Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
(2)使用扩展
<serviceBehaviors>
<behavior name="DefaultBehavior">
<serviceMetadata httpGetEnabled="true" httpGetUrl="" />
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceThrottling maxConcurrentCalls="200" maxConcurrentInstances="200" maxConcurrentSessions="200" /> <dataContractSerializer maxItemsInObjectGraph="2147483647" />
<Test/> <!--上文中扩展定义的名称-->
</behavior>
</serviceBehaviors>