我正在尝试将 api key 附加到 OperationContext 传出消息 header ,如下所示:
public static void AddApikeyToHeader(string apikey, IContextChannel channel, string address)
{
using (OperationContextScope scope = new OperationContextScope(channel))
{
MessageHeader header = MessageHeader.CreateHeader("apikey", address, apikey);
OperationContext.Current.OutgoingMessageHeaders.Add(header);
}
}
但是我不知道如何在服务器端检索 header 。我正在使用服务授权管理器,我获得了当前的操作上下文并尝试像这样检索 header :
public string GetApiKey(OperationContext operationContext)
{
var request = operationContext.RequestContext.RequestMessage;
var prop = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
return prop.Headers["apikey"];
}
但那里没有附加 apikey header 。此外,在调试时,当我检查 operationContext 时,我似乎无法在任何地方看到我的 apikey header 。谁能看出我哪里出错了?
最佳答案
您可以通过这种方式添加自定义 header :
using (ChannelFactory<IMyServiceChannel> factory =
new ChannelFactory<IMyServiceChannel>(new NetTcpBinding()))
{
using (IMyServiceChannel proxy = factory.CreateChannel(...))
{
using ( OperationContextScope scope = new OperationContextScope(proxy) )
{
Guid apiKey = Guid.NewGuid();
MessageHeader<Guid> mhg = new MessageHeader<Guid>(apiKey);
MessageHeader untyped = mhg.GetUntypedHeader("apiKey", "ns");
OperationContext.Current.OutgoingMessageHeaders.Add(untyped);
proxy.DoOperation(...);
}
}
}
和服务端,你可以得到这样的标题:
Guid apiKey =
OperationContext.Current.IncomingMessageHeaders.GetHeader<Guid>("apiKey", "ns");
关于c# - 从请求上下文中添加和检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7670666/