WCF使用OperationContext添加和获取头信息
使用网上的例子
使用WCF头信息可以用于在调用Service的同时传递Header元数据
客户端:
ChannelFactory<IOrderProcessor> channelFactory = new ChannelFactory<IOrderProcessor>("defaultEndpoint");
IOrderProcessor orderProcessor = channelFactory.CreateChannel();
//使用通道建立Scope
using (OperationContextScope scope = new OperationContextScope(orderProcessor as IContextChannel))
{
MessageHeader<string> mh = new MessageHeader<string>("abcde");
MessageHeader header = mh.GetUntypedHeader("AuthKey", http://www.cjb.com/);//设置名称和命名空间
OperationContext.Current.OutgoingMessageHeaders.Add(header);
orderProcessor.Function();//调用服务时发送的数据Header为在该OperationContextScope中设置的OperationContext
}
服务端:IOrderProcessor orderProcessor = channelFactory.CreateChannel();
//使用通道建立Scope
using (OperationContextScope scope = new OperationContextScope(orderProcessor as IContextChannel))
{
MessageHeader<string> mh = new MessageHeader<string>("abcde");
MessageHeader header = mh.GetUntypedHeader("AuthKey", http://www.cjb.com/);//设置名称和命名空间
OperationContext.Current.OutgoingMessageHeaders.Add(header);
orderProcessor.Function();//调用服务时发送的数据Header为在该OperationContextScope中设置的OperationContext
}
//OperationContext.Current 返回当前建立连接的OperationContext
if (OperationContext.Current != null)
{
authKey = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>("AuthKey", http://www.cjb.com);
}
if (OperationContext.Current != null)
{
authKey = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>("AuthKey", http://www.cjb.com);
}