无法使IDispatchMessageInspector工作

时间:2012-08-30 14:36:43

标签: wcf idispatchmessageinspector

我需要在REST,Json,WCF Web服务中使用请求标头。 我创建了我的IDispatchMessageInspector

public class HeaderInspector : IDispatchMessageInspector
{
    public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
    {
        int ind = request.Headers.FindHeader("xxxxx", "");
        return null;
    }

    public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
    {
    }
}

然后一个endpointbehavio将检查员附加到端点:

public class HeaderInspectorBehavior : IEndpointBehavior
{
    public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
    {
    }

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

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

    public void Validate(ServiceEndpoint endpoint)
    {
    }
}

最后是一个BehaviorExtensionElement:

public class MyExtension : BehaviorExtensionElement
{
    public override Type BehaviorType
    {
        get { return typeof(HeaderInspectorBehavior); }
    }
    protected override object CreateBehavior()
    {
        return new HeaderInspectorBehavior();
    }
}

这些类位于同一文件/命名空间PDM.WebService中 我的配置是:

<behaviors>
  <endpointBehaviors>
    <behavior name="RestBehavior">
      <HeaderInspectorBehavior/>
      <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json" faultExceptionEnabled="true" automaticFormatSelectionEnabled="false" />
    </behavior>
  </endpointBehaviors>
</behaviors>
<extensions>
  <behaviorExtensions>
    <add name="HeaderInspectorBehavior" type="PDM.WebService.MyExtension, PDM.WebService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
  </behaviorExtensions>
</extensions>

一切编译得很好,在执行时我可以捕获方法“public override Type BehaviorType”的执行, 但之后没有其他方法的代码被触发(我发送了请求,我得到了响应,服务响应很好)。 我在每个方法中设置调试点,没有别的执行! (尤其是ApplyDispatchBehavior)。 有人可以指出我错过的东西吗?

1 个答案:

答案 0 :(得分:0)

有关类似问题,请参阅CreateBehavior() is not invoked

确保您的服务元素的名称与mynamespace.myservicename

相对应

即使您没有正确的服务名称,该服务也会提供正确的响应;但只有在您具有正确的服务元素名称时才会调用CreateBehavior()

实施例

<service
      name="WcfServiceApp001.Service1"
      behaviorConfiguration="InternalPayrollBehavior">
<endpoint address="" binding="basicHttpBinding"
          behaviorConfiguration="EndpointBehavior"
          contract="WcfServiceApp001.IService1"
          />
</service>