一 需求
服务端每次为客户端提供服务调用时,需要知道客户端的标识。客户端如何在每次调用时传递此标识?
二 解决
客户端
static void HandleFactory(ChannelFactory factory) { Debug.Assert(factory != null && factory.Credentials != null); factory.Endpoint.Behaviors.Add(new ClientMessageInspector{ HeaderValue=new []{"哈啰"} }); } private class ClientMessageInspector : System.ServiceModel.Dispatcher.IClientMessageInspector, System.ServiceModel.Description.IEndpointBehavior { public string HeaderValue { get; set; } #region Implementation for IClientMessageInspector public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState) { } public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel) { request.Headers.Add(System.ServiceModel.Channels.MessageHeader.CreateHeader("id", "client", HeaderValue)); return null; } #endregion #region Implementation for IEndpointBehavior //================================== public void AddBindingParameters(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) { } public void ApplyClientBehavior(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, ClientRuntime behavior) { //此处为Extension附加到ClientRuntime。 behavior.MessageInspectors.Add(this); } public void ApplyDispatchBehavior(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint, EndpointDispatcher endpointDispatcher) { //如果是扩展服务器端的MessageInspector,则要附加到EndpointDispacther上了。 //endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this); } public void Validate(System.ServiceModel.Description.ServiceEndpoint serviceEndpoint) { } #endregion }
服务端
var clientId=OperationContext.Current.IncomingMessageHeaders.GetHeader<string>("id","client");
三 参考
Writing a WCF Message Inspector
利用定制行为扩展WCF之-利用MessageInsepctor behaviourExtension扩展WCF行为(自定义消息头)