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

    勉強心を持てば、生活は虚しくない!
  • 相关阅读:
    Django创建超级用户出现错误
    如何创建单例设计模式
    运行Spark-shell,解决Unable to load native-hadoop library for your platform
    在linux上安装spark详细步骤
    Spark源码编译,官网学习
    linux安装httpd,做文件服务器
    在linux上安装Scala详细步骤
    hadoop运行wordcount实例,hdfs简单操作
    hadoop-2.6.0源码编译问题汇总
    hadoop-2.6.0源码编译
  • 原文地址:https://www.cnblogs.com/beta2013/p/3377307.html
Copyright © 2020-2023  润新知