我需要在 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>
一切都编译得很好,在执行时我可以捕捉到方法“public override Type BehaviorType”的执行,但之后没有其他代码方法被触发(我发送了请求并得到了响应,服务响应良好)。我在每个方法中都设置了调试点,没有其他方法执行!(尤其是 ApplyDispatchBehavior)。有人可以指出我缺少什么吗?