Dim*_*tar 5 c# wcf asp.net-mvc-3
我正在尝试将api密钥附加到OperationContext传出消息头,如下所示:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
但后来我不知道如何检索服务器端的标头.我正在使用服务授权管理器,我得到当前的操作上下文并尝试检索这样的标题:
public string GetApiKey(OperationContext operationContext)
{
var request = operationContext.RequestContext.RequestMessage;
var prop = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
return prop.Headers["apikey"];
}
Run Code Online (Sandbox Code Playgroud)
但那里没有附加的apikey标题.另外,在我检查operationContext的时候调试我似乎无法在任何地方看到我的apikey头.谁能看到我哪里出错了?
Upe*_*ari 14
您可以通过以下方式添加自定义标头:
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(...);
}
}
}
Run Code Online (Sandbox Code Playgroud)
而服务方面,您可以获得如下标题:
Guid apiKey =
OperationContext.Current.IncomingMessageHeaders.GetHeader<Guid>("apiKey", "ns");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13369 次 |
| 最近记录: |