2012-08-30 45 views
3

我需要在REST,Json和WCF Web服務中使用請求標頭。 創建我IDispatchMessageInspector無法使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(); 
    } 
} 

這些類在同一個文件/命名空間是我的配置是:

<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)。 有人可以指出我錯過了什麼嗎?

回答

0

有關類似問題,請參閱CreateBehavior() is not invoked

確保您的服務元素的該名稱對應mynamespace.myservicename

這項服務將提供正確的響應,即使你沒有正確的服務名稱;但CreateBehavior()只有在服務元素的名稱正確時纔會被調用。

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