IDIspatchMessageInspector

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)
    {
    }
}


然后是一个端点,将检查器附加到端点:

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>


一切都编译良好,在执行时我可以捕获方法“公共重写类型BehaviorType”的执行,
但此后没有其他代码方法被触发(我发送了请求,得到响应,服务响应良好)。
我在所有其他方法中都设置了调试点! (尤其是ApplyDispatchBehavior)。
有人可以指出我所缺少的吗?

最佳答案

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

确保服务元素的名称与mynamespace.myservicename相对应

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



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

关于wcf - 无法使IDispatchMessageInspector工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12199373/

10-10 11:18