zoukankan      html  css  js  c++  java
  • 扩展WCF行为,自定义消息头,实现客户端标识的传递

    一 需求

    服务端每次为客户端提供服务调用时,需要知道客户端的标识。客户端如何在每次调用时传递此标识?


    二 解决

    客户端

    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行为(自定义消息头)

    勉強心を持てば、生活は虚しくない!
  • 相关阅读:
    js控制滚动条滑动
    js二维码插件总结
    wer
    验证插件——jquery.validate.js
    .py小程序总结
    Linux中xargs命令的使用
    Cacti、解决cacti的snmp error
    Cacti安装使用
    用Python发一个高逼格的朋友圈
    windows安装zabbix-agent
  • 原文地址:https://www.cnblogs.com/beta2013/p/3377307.html
Copyright © 2011-2022 走看看